Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse this escaped Json with Gson java?

Tags:

java

json

gson

So I'm getting responses like the following which I have no control over:

{
    "message": "someName someLastName has sent you a question",
    "parameters": "{\"firstName\":\"someName\",\"lastName\":\"someLastName\"}",
    "id": 141
}

At a glance it seems simple, but the parameters element needs to be read as a json object and I cannot for the life of me work out how to do it. This is what I am trying at the moment:

JsonObject parameters = data.getAsJsonObject().get("parameters").getAsJsonObject();
/throws java.lang.IllegalStateException: Not a JSON Object: "{\"firstName\":\"someName\",\"lastName\":\"someLastName\"}"

So I tried:

String elementToString = data.getAsJsonObject().get("parameters").toString().replace("\\\"", "\"");
JsonObject parameters = new Gson().fromJson(elementToString, JsonElement.class).getAsJsonObject();
//throws com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 5 path $

Where data is (typically this is pulled from a server):

JsonElement data = new Gson().fromJson("  {\n" +
        "    \"message\": \"someName someLastName has sent you a question\",\n" +
        "    \"parameters\": \"{\\\"firstName\\\":\\\"someName\\\",\\\"lastName\\\":\\\"someLastName\\\"}\",\n" +
        "    \"id\": 141\n" +
        "  }", JsonElement.class);

Surely this is not a difficult problem?

like image 299
Joe Maher Avatar asked Dec 23 '15 01:12

Joe Maher


People also ask

What is Gson parser in JSON?

Gson – JsonParser Gson JsonParser is used to parse Json data into a parse tree of JsonElement and thus JsonObject. JsonObject can be used to get access to the values using corresponding keys in JSON string. 1.

What is the best way to parse JSON?

These two (org.json and Gson) are the most common ways which are used by developers to parse the JSON. And these two approaches require full deserialization of the JSON into a Java object before accessing the property of our choice from the JSON.

How do I read a JSON object in Java?

Gson allows you to read JSON into a tree model: Java objects that represent JSON objects, arrays and values. These objects are called things like JsonElement or JsonObject and are provided by Gson. Start by instantiating a JsonParser then call .parse to get a JsonElement which can be descended through to retrieve nested values.

How to convert JSON file to Java object?

JSON file to Java object Object object = gson.fromJson(new FileReader("C:\fileName.json"), Object.class); // 2. JSON string to Java object String json = "{'name' : 'mkyong'}"; Object object = gson.fromJson(json, Staff.class); 1. Download Gson pom.xml


2 Answers

What you have here

"parameters": "{\"firstName\":\"someName\",\"lastName\":\"someLastName\"}",

is a JSON pair where both the name (which is always a JSON string) and the value are JSON strings. The value is a String that can be interpreted as a JSON object. So do just that

String jsonString = data.getAsJsonObject().get("parameters").getAsJsonPrimitive().getAsString(); 
JsonObject parameters = gson.fromJson(jsonString, JsonObject.class);

The following

Gson gson = new Gson();
JsonElement data = gson
        .fromJson("  {\n" + "    \"message\": \"someName someLastName has sent you a question\",\n"
                + "    \"parameters\": \"{\\\"firstName\\\":\\\"someName\\\",\\\"lastName\\\":\\\"someLastName\\\"}\",\n"
                + "    \"id\": 141\n" + "  }", JsonElement.class);
String jsonString = data.getAsJsonObject().get("parameters").getAsJsonPrimitive().getAsString(); 
JsonObject parameters = gson.fromJson(jsonString, JsonObject.class);
System.out.println(parameters);

prints the JSON text representation of that JsonObject

{"firstName":"someName","lastName":"someLastName"}
like image 149
Sotirios Delimanolis Avatar answered Nov 05 '22 21:11

Sotirios Delimanolis


The solution I use to get the concrete object (regardless whether it's already an object, or an escaped string) is a deserializer like this:

public class MyDeserializer implements JsonDeserializer<MyThing> {

    @Override
    public MyThing deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (element.isJsonObject()) {
            //Note Don't use a gson that contains this deserializer or it will recurse forever
            return new Gson().fromJson(element.getAsJsonObject(), MyThing.class);
        } else {
            String str = element.getAsJsonPrimitive().getAsString();
            return gson.get().fromJson(str, MyThing.class);
        }
    }    

}
like image 21
Nick Cardoso Avatar answered Nov 05 '22 20:11

Nick Cardoso