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);

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

I obtain the following exception org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1].
@baraky - this will not work. It will just surround the entire JSON string with quotes, not the individual fields and values.
@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 `\`.
Did you try JSONObject(myMap)?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.