Java – How to parse JSON using GSON escape quotes

How to parse JSON using GSON escape quotes… here is a solution to the problem.

How to parse JSON using GSON escape quotes

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

I tried to parse it to

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

And get the exception

Caused by: com.google.gson.stream.MalformedJsonException: The expected name at the path $[0] in line 1, column 3.

Edit
By far the best solution is to add
Compile 'org.apache.commons:commons-lang3:3.5' dependencies and use gson.fromJson(StringEscapeUtils.unescapeJson(response.body()), RouteModel[].class).

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

Solution

Using disableHtmlEscaping should solve the problem without ugly workarounds.
I also use prettyPrinting to get better output….

Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
gson.from(response.body(), RouteModel[].class)

Related Problems and Solutions