I have a json string as below:
{"person":[{"initials":"C. P.","familyName":"Mangum"}],"title":"Blood and tissue oxygen carriers","text":"(ed). \992d. Springer-Verlag, Heidelberg"}
When de-serializing above json string using gson as below:
gson.fromJson(json, MyObject.class)
I see MalformedJsonException
exception.
Caused by: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Invalid escape sequence at line 1 column 115 path $.test
Then I tried setting JsonReader
setLenient to true
JsonReader reader = new JsonReader(new StringReader(row));
reader.setLenient(true);
gson.fromJson(reader, MyObject.class);
But now I get ClassCastException
now:
Caused by: java.lang.ClassCastException: class MyObject cannot be cast to class com.google.gson.JsonElement (MyObject and com.google.gson.JsonElement are in unnamed module of loader 'app')
Later I tried using setLenient() in GsonBuilder, but it failed with original MalformedJsonException
exception
Gson gson = new GsonBuilder().setLenient().create();
gson.fromJson(row, MyObject.class);
I am not sure if I can use theString = theString.replace("\\", "\\\\");
is safe. Is there good practice to be followed?
Can I please know how I can process escaped characters as above?
json is malformed, it should have a double \ for \\992d
in the original form:
{
"person": [{
"initials": "C. P.",
"familyName": "Mangum"
}],
"title": "Blood and tissue oxygen carriers",
"text": "(ed). \\992d. Springer-Verlag, Heidelberg"
}
You need to escape your "text" element as below, then it will be a valid json.
{
"person": [{
"initials": "C. P.",
"familyName": "Mangum"
}],
"title": "Blood and tissue oxygen carriers",
"text": "(ed). \\992d. Springer-Verlag, Heidelberg"
}
Apache Commons
If you're already using Apache commons, it provides a static method for this:
StringEscapeUtils.escapeJson("some string")
It converts any string into one that's properly escaped for inclusion in JSON.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.