Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing an object that contains JSON using GSON

Tags:

java

json

gson

I'm using gson to deserialize POJO objects from JSON representations.

I'd like one of the fields in one of my POJOs to contain arbitrary JSON data. For example:

class B {
    public String stringField;
    public JsonObject jsonField;
}

I'd like to be able to call Gson.fromJson(json, B.class) on the following JSON:

{
    "stringField": "booger",
    "jsonField" :
    {
        "arbitraryField1": "foo"
    }
}

and have the resulting B.jsonField contain a JsonObject with an arbitraryField of value foo.

However, when I attempt to do this, jsonField is always an empty object ({}). In fact, more generally, it appears that the following always returns an empty object:

new Gson().fromJson("{ foo: 1 }", JsonObject.class)

I would expect the above to return an object containing a field named foo of value 1.

How can I have gson preserve arbitrary json data when deserializing json to POJOS?

like image 255
emmby Avatar asked Feb 19 '23 04:02

emmby


1 Answers

I was able to work around the problem by introducing a wrapper object that contains a JsonObject, and then writing a custom deserializer for that object that simply returns the original json. However, it seems like there must be a better way.

For posterity, the deserializer and the trivial wrapper object look like the following:

class MyJsonObjectWrapperDeserializer implements JsonDeserializer<MyJsonObjectWrapper> {
    @Override
    public MyJsonObjectWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return new MyJsonObjectWrapper(json.getAsJsonObject());
    }
}

class MyJsonObjectWrapper {
    public JsonObject json;

    public MyJsonObjectWrapper(JsonObject json) {
        this.json = json;
    }
}
like image 97
emmby Avatar answered Mar 02 '23 22:03

emmby