1

I'm using the library org.json.

I have a string like this (quotes can't appear in field_n)

{field1=value1, field2=value2}  (say it `val`)

This string is obtained from an Hashtable<String, Object>.

I create a JSONObject from that string, obtaining:

{"field1":"value1", "field2":"value2"}

The issue arises when in the value value_n quotes (or newlines and carriage return) appear.

I've tried to escape the string in this way:

value = value.replace("\\", "\\\\");
value = value.replace("\"", "\\\"");
value = value.replace("\r", "\\r");
value = value.replace("\n", "\\n");

but I always obtain the org.json.JSONException: Expected a ',' or '}' at ... [character ... line 1] when I try to create the JSONObject with:

JSONObject json = new JSONObject(val);
Sefran2
  • 3,578
  • 13
  • 71
  • 106

1 Answers1

0

In order to create JSON from map, use:

new JSONObject(myMap);

Another related issue:

quotedStr = JSONObject.quote(val.trim());

will qoute all needed values as it says:

Produce a string in double quotes with backslash sequences in all the right places

BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
  • I obtain the following exception `org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]`. – Sefran2 Feb 25 '13 at 14:16
  • @baraky - this will not work. It will just surround the entire JSON string with quotes, not the individual fields and values. – Perception Feb 25 '13 at 14:20
  • See if it can help: http://stackoverflow.com/questions/4773663/jsonobject-text-must-begin-with – BobTheBuilder Feb 25 '13 at 14:26
  • @baraky: nothing. Exception `org.json.JSONException: Expected a ',' or '}' at ... [character ... line 1]` is raised. The string is escaped (`{field1=dfds \"fdsfs\" fdfsd, field2=dsad\r\nfgfgfd}`), but the JSONObject construction fails at the first `\\`. – Sefran2 Feb 25 '13 at 14:47
  • maybe you can use JSONObject.quote() on every object inside the JSON (what you get from the map) and just add "{" and "}" at the beginning and end. – BobTheBuilder Feb 25 '13 at 14:52
  • And you can look at http://stackoverflow.com/questions/512692/listmapstring-object-to-org-json-jsonobject – BobTheBuilder Feb 25 '13 at 14:55
  • 1
    Did you try JSONObject(myMap)? – BobTheBuilder Feb 25 '13 at 14:56