Gson – deserialization to specific object type based on field value

You may implement a JsonDeserializer and use it while parsing your Json value to a Java instance. I’ll try to show it with a code which is going to give you the idea:

1) Define your custom JsonDeserializer class which creates different instance of classes by incoming json value’s id property:

class MyTypeModelDeserializer implements JsonDeserializer<MyBaseTypeModel> {

    @Override
    public MyBaseTypeModel deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
            throws JsonParseException {

        JsonObject jsonObject = json.getAsJsonObject();

        JsonElement jsonType = jsonObject.get("type");
        String type = jsonType.getAsString();

        MyBaseTypeModel typeModel = null;     

        if("type1".equals(type)) {
            typeModel = new Type1Model();
        } else if("type2".equals(type)) {
            typeModel = new Type2Model();
        }
        // TODO : set properties of type model

        return typeModel;
    }
}

2) Define a base class for your different instance of java objects:

class  MyBaseTypeModel {
    private String type;
    // TODO : add other shared fields here
}

3) Define your different instance of java objects’ classes which extend your base class:

class Type1Model extends MyBaseTypeModel {
    // TODO: add specific fields for this class
}

class Type2Model extends MyBaseTypeModel {
    // TODO: add specific fields for this class
}

4) Use these classes while parsing your json value to a bean:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(MyBaseTypeModel.class, new MyTypeModelDeserializer());
Gson gson = gsonBuilder.create();

MyBaseTypeModel myTypeModel = gson.fromJson(myJsonString, MyBaseTypeModel.class);

I can not test it right now but I hope you get the idea. Also this link would be very helpful.

Leave a Comment