0

... I am experiencing an anomaly that I do not understand why. The scenario is as follows:

1.- From JSP, using JS, I send data in JSON format to a servlet.

  JSON:  "{'ORDER': '1', 'DATE': '06-01-2018', 'TIME': '07:06:51', 'BOUCHER': '208896.0', 'LIC' : 'HSGR30', 'QTY': '0.0'} "

2.- I capture the data, with the getParameter utility, on a String type variable.

3.- I pass the variable to the JSONObject utility, and it does not process it since there are two "" (two double quotes) in that variable, and debugging the class (JSONObject) throws an exception because the first character of the string is not "{" ... which is logical.

4.- Now, if I take the complete stream and paste it in the call:

JSONObject obj = new JSONObject ("{'ORDER': '1', 'DATE': '06-01-2018', 'TIME': '07:06:51', 'BOUCHER': '208896.0' , 'LIC': 'HSGR30', 'QTY': '0.0'} ") 

It processes it correctly and I get the object with its associated properties and values.

I was considering that the JSON format I send from JS is not valid???. But I can't find the cause of why???

The problem is that I don't understand why two double quotes appear.

If you can give me a hand with this,

thank you very much !!!

andrewJames
  • 19,570
  • 8
  • 19
  • 51
Chalie
  • 1
  • 2
  • Strings in JSON are supposed to use double quotes, e.g. `"ORDER": "1"` instead of `'ORDER': '1'`. Other than that, your JSON looks valid, although you may want to store numbers such as `QTY` as numbers rather than strings, e.g. drop the quotes, for more efficiency. – Eric Reed Jun 18 '20 at 00:56
  • You can use a JSON validator - for example [this one](https://jsonlint.com/). You will see the point made by EricReed about `"` vs `'`. – andrewJames Jun 18 '20 at 01:15

2 Answers2

0

use double quotes: " instead of single quotes: ' and use \ before each doublquote to escape the characters.

E.g:

JSONObject obj = new JSONObject ("{\"ORDER\": \"1\",\"DATE\": \"06-01-2018\",\"TIME\": \"07: 06: 51\",\"BOUCHER\": \"208896.0\",\"LIC\": \"HSGR30\",\"QTY\": \"0.0\"}"); 
Tony
  • 436
  • 1
  • 9
  • 17
0

Very grateful for your prompt replies.

I found the problem, in the js code I was doing JSON.stringify(). I remove it and everything is fine.

I just need to rethink how to send, from js, package JSON formatted records.

It was not clear how JSONObject handles the string it receives.

I guess I'll have to rethink an array of JSON objects and then send it. Perhaps, by receiving array object type, it will understand that it is a batch of records.

Thanks again

Chalie
  • 1
  • 2