Joe Maher
Joe Maher

Reputation: 5460

How do I parse this escaped Json with Gson java?

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?

Upvotes: 11

Views: 11477

Answers (2)

Nick Cardoso
Nick Cardoso

Reputation: 21733

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);
        }
    }    

}

Upvotes: 2

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

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"}

Upvotes: 17

Related Questions