Gson - deserialization to specific object type based on field value

后端 未结 4 678
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 06:33

I want to deserialize json objects to specific types of objects (using Gson library) based on type field value, eg.:

[
    {
          \"type\":         


        
4条回答
  •  星月不相逢
    2020-12-01 07:20

    use https://github.com/google/gson/blob/master/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java

    then configure it with

    public static final class JsonAdapterFactory extends 
        RuntimeTypeAdapterFactory {
            public JsonAdapterFactory() {
                super(MyBaseType.class, "type");
                registerSubtype(MySubtype1.class, "type1");
                registerSubtype(MySubtype2.class, "type2");
            }
    }
    

    and add the annotation:

    @JsonAdapter(MyBaseType.JsonAdapterFactory.class)

    to MyBaseType

    Much better.

提交回复
热议问题