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

Nic*_*oso 13 java generics android gson

我有大致以下结构

class MyDeserialParent<T extends MyChildInterface> {

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

}
Run Code Online (Sandbox Code Playgroud)

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

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

显然,这使我无法仅仅通过注释mSerialChild SerializedName并让它TypeAdapter发挥作用.那么,我希望做的是,当MyDeserialParent被deserialised使用"类型",找到正确的具体类的MyChildInterface,并使用一个新的childProp1,并childProp2作为params用于在构造函数.我不知道怎么回事.

我可以想象使用a TypeAdapter(JsonDeserializer)for MyDeserialParent和in deserialize获取类型字段(以及两个子属性),然后为MyChildInterface我自己实例化正确的具体.

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

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

Der*_*lin 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

评论:

  • 自定义适配器必须在 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
Run Code Online (Sandbox Code Playgroud)

家长:

class MyDeserialParent<T extends MyChildInterface>{

    MyChildInterface mSerialChild;
    //some other fields (not 'type')
    String otherProp;
}
Run Code Online (Sandbox Code Playgroud)

孩子:

public class MyChild1 implements MyChildInterface {
    String childProp1;
    String childProp2;
}//end class
Run Code Online (Sandbox Code Playgroud)