I am trying to get an array of objects from the server, using JSON.
The server sends me the following string.
\"[{\\\"DealComment\\\":null,\\\"DealVo
Try this:
String jsonFormattedString = jsonStr.replaceAll("\\\\", "");
Because the backslash is the escaping character in a regular expression (replaceAll()
receives one as parameter), it has to be escaped, too.
You can just use:
str.replace("\\","");
replace takes string as param, replaceAll uses RegEx. it may work like this also:
str.replaceAll("\\\\", "");
jsonObj.toString()
.replace("\"[", "[").replace("]\"", "]")
.replace("\\\"{", "{").replace("}\\\"", "}")
.replace("\\\\\\\"", "\"")
It looks like your incoming string is doubly JSON encoded. You should decode it, then decode that again.
Here's my best guess as to how you might do that in Java:
JSONArray resultArray = new JSONArray(new JSONString(jsonFormattedString));
I'm assuming here that JSONString
is a type. Your actual solution may vary.
Under normal circumstances, I'd expect a service to give you JSON straight up. It appears that this services is giving you a string (encoded according to the JSON spec) which contains JSON.
It's the difference between the following:
String someJSON = "[0, 1, 2]";
String doublyEncodedJSON = "\"[0, 1, 2]\"";
Notice the extra leading and trailing quotes? That's because the latter is a string of JSON. You'd have to decode it twice to get the actual object.
Actually the correct way would be:
String jsonFormattedString = jsonStr.replace("\\\"", "\"");
You want to replace only \"
with "
, not all \
with nothing (it would eat up your slashes in json strings, if you have ones).
Contrary to popular believe replace(...)
also replaces all occurrences of given string, just like replaceAll(...)
, it just doesn't use regexp so it usually be faster.
Just use:
try {
jsonFormattedString = new JSONTokener(jsonString).nextValue().toString();
} catch (JSONException e) {
e.printStackTrace();
}
See documentation