使用GSON反序列化父对象的params实例化子对象并使用泛型?

时间:2016-02-09 15:06:02

标签: java android generics gson

我大致有以下结构

class MyDeserialParent<T extends MyChildInterface> {

     MyChildInterface mSerialChild;
     ... //some other fields (not 'type')

}

但是它从一个混乱的JSON结构中反序列化,子节点的两个属性在父节点上返回,如下所示。

{
    "myDeserialParents" : [
        {
            ... //some parent properties
            "type": "value", //used in a TypeAdapter to choose child implementation
            "childProp1": "1",
            "childProp2": "2",
         },
         ... //more in this list
     ]
}

显然,这使我无法仅使用SerializedName注释mSerialChild并让TypeAdapter发挥其魔力。所以我希望做的是当MyDeserialParent反序列化时使用&#34;键入&#34;找到MyChildInterface的正确具体类,并使用childProp1childProp2作为构造函数的参数创建一个新类。我不知道如何解决这个问题。

我可以想象使用TypeAdapterJsonDeserializer)作为MyDeserialParent并在deserialize中获取类型字段(以及两个子属性),然后实例化为MyChildInterface我自己纠正具体内容。

这意味着我必须创建我的MyDeserialParent类(使用context.deserialize(json, MyDeserialParent.class))并使用MyChildInterface实例调用setter。那种感觉错了,就像我错过了什么。还有更好的方法吗?

如果手动创建父对象,是否还有一种方法可以指定泛型(T上的MyDeserialParent)?或类型擦除是否意味着没有办法做到这一点? (这个问题不太重要,因为我知道如果我使用已经推断T的MyDeserialParent的特定子类型,我可以获得类型安全性,但我想避免它)

1 个答案:

答案 0 :(得分:3)

您显然需要自定义TypeAdapter。但棘手的部分是:

  • 您的父类是通用的
  • mSerialChild不属于T类型,但类型为MyChildInterface
  • 我们希望避免手工解析每个子类的json,并且能够向父级添加属性而无需修改整个代码。

记住这一点,我最终得到了以下解决方案。

public class MyParentAdapter implements JsonDeserializer<MyDeserialParent>{

    private static Gson gson = new GsonBuilder().create();
    // here is the trick: keep a map between "type" and the typetoken of the actual child class
    private static final Map<String, Type> CHILDREN_TO_TYPETOKEN;

    static{
        // initialize the mapping once
        CHILDREN_TO_TYPETOKEN = new TreeMap<>();
        CHILDREN_TO_TYPETOKEN.put( "value", new TypeToken<MyChild1>(){}.getType() );
    }


    @Override
    public MyDeserialParent deserialize( JsonElement json, Type t, JsonDeserializationContext
            jsonDeserializationContext ) throws JsonParseException{
        try{
            // first, get the parent
            MyDeserialParent parent = gson.fromJson( json, MyDeserialParent.class );
            // get the child using the type parameter
            String type = ((JsonObject)json).get( "type" ).getAsString();
            parent.mSerialChild = gson.fromJson( json, CHILDREN_TO_TYPETOKEN.get( type ) );
            return parent;

        }catch( Exception e ){
            e.printStackTrace();
        }
        return null;
    }
}

说明:

  • 自定义适配器必须在gsonBuilder上注册
  • 如果你的孩子需要一些自定义gson属性,你可以在Gson的构造函数中传递MyParentAdapter对象,因为它现在使用默认值;
  • 子级和父级必须具有不同名称的属性;
  • 必须使用相应的类将每个新类型添加到地图中。

完整示例

主要:

public class DeserializeExample{

    MyDeserialParent[] myDeserialParents;

    static String json = "{\n" +
            "    \"myDeserialParents\" : [\n" +
            "        {\n" +
            "            \"otherProp\": \"lala\"," +
            "            \"type\": \"value\", //used in a TypeAdapter to choose child implementation\n" +
            "            \"childProp1\": \"1\",\n" +
            "            \"childProp2\": \"2\"\n" +
            "         }\n" +
            "     ]\n" +
            "}";


    public static void main( String[] args ){
        Gson gson = new GsonBuilder().registerTypeAdapter( MyDeserialParent.class, new MyParentAdapter() ).create();
        DeserializeExample result = gson.fromJson( json, DeserializeExample.class );
        System.out.println( gson.toJson( result ));
        // output: 
        // {"myDeserialParents":[{"mSerialChild":{"childProp1":"1","childProp2":"2"},"otherProp":"lala"}]}
    }//end main

}//end class

父:

class MyDeserialParent<T extends MyChildInterface>{

    MyChildInterface mSerialChild;
    //some other fields (not 'type')
    String otherProp;
}

子:

public class MyChild1 implements MyChildInterface {
    String childProp1;
    String childProp2;
}//end class