Send JSON Data From JavaScript to a Servlet

168 Views Asked by At

... 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 !!!

2

There are 2 best solutions below

0
Tony On

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\"}"); 
0
Chalie On

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