Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON which has escaped quotes with GSON

Tags:

java

json

gson

I have following JSON [{\"X\":24.0124010872935,\"Y\":49.7740722529036,\"Code\":\"0320\",\"Name\": .....]

I try to parse it as

Gson gson = new Gson();
gson.fromJson(response.body(), RouteModel[].class)

And got Exception

Caused by: com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 3 path $[0].

EDIT So far the best solution was to add compile 'org.apache.commons:commons-lang3:3.5' dependency and use gson.fromJson(StringEscapeUtils.unescapeJson(response.body()), RouteModel[].class)

Or just simply use replace("\\\"","\"")

like image 640
Roman Nazarevych Avatar asked Sep 18 '25 02:09

Roman Nazarevych


1 Answers

Using disableHtmlEscaping should solve the problem without ugly workarounds. Also I used prettyPrinting to have a nicer output....

Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
gson.from(response.body(), RouteModel[].class)
like image 101
Jordi Castilla Avatar answered Sep 20 '25 16:09

Jordi Castilla