Practical Gson — 如何解析多态对象

原文链接:Practical Gson — How to Deserialize a List of Polymorphic Objects
原文出自:Norman Peitek
译者:無名無

当我们接受收一个 JSON 列表数据时,正常来说我们使用 Gson 就可以帮我们解析,但是如果我们要解析成的对象是多态的,并且需要解析子类特定的字段,前面的解决方案只能应对一个 Java model 解析,如果我们还这么做,显然是得不到自己想要的数据的,所以需要寻找一个更好的解决方案。很多人会编写一个自定义的de / serializer,这虽然是一个解决办法,但要写很多代码。 最后,发现了使用 RuntimeTypeAdapterFactory 可以解决了解析多态的问题。

多态实例

public class Animal {  
    private String name;
        private String type; // this specifies which animal it is
    }

    public class Dog extends Animal {
        private boolean playsCatch;
    }

    public class Cat extends Animal {
        private boolean chasesRedLaserDot;
    }
}

想象我们有一个动物的 List 数据,包含了一些无序各种动物信息。

如何解决

使用 RuntimeTypeAdapterFactory 类解决多态问题,但是这个类需要单独下载,githut地址 RuntimeTypeAdapterFactory.java ,并没有存在 Gson 包中。

String responseJson = new String(responseBody); // from the service endpoint

// which format has the response of the server
final TypeToken requestListTypeToken = new TypeToken() {};

// adding all different container classes with their flag
final RuntimeTypeAdapterFactory typeFactory = RuntimeTypeAdapterFactory  
        .of(Animal.class, "type") // Here you specify which is the parent class and what field particularizes the child class.
        .registerSubtype(Dog.class, "dog") // if the flag equals the class name, you can skip the second parameter. This is only necessary, when the "type" field does not equal the class name.
        .registerSubtype(Cat.class, "cat");

// add the polymorphic specialization
final Gson gson = new GsonBuilder().registerTypeAdapterFactory(typeFactory).create();

// do the mapping
final ServiceResponse deserializedRequestList = gson.fromJson(responseJson, requestListTypeToken.getType() );  

使用方法也可以查看 RuntimeTypeAdapterFactory 类中的注释。

注意:如果服务器返回一个客户端没有定义的类型,会导致出问题。

目标

学习使用 RuntimeTypeAdapterFactory 解决多态问题。

练习代码已上传 Github https://github.com/whiskeyfei/Gson-Review 可自行查看。

Gson 系列文章翻译回顾

1、Gson - Java-JSON 序列化和反序列化入门
2、Gson - 映射嵌套对象
3、Gson - Arrays 和 Lists 映射对象
4、Gson - Map 结构映射
5、Gson - Set 集合映射
6、Gson - 空值映射
7、Gson Model Annotations - 如何使用 @SerializedName 更改字段的命名
8、Gson Model Annotations - @SerializedName 匹配多个反序列化名称
9、Gson Builder - 基础和命名规则
10、Gson Builder - 序列化空值
11、Gson Builder - 忽略策略
12、Gson Builder - Gson Lenient 属性
13、Gson Builder - 特殊类型 Floats & Doubles
17、Gson Builder - 如何使用 @Expose 忽略字段
19、Gson Advanced - 映射枚举类型
20、Gson Advanced - 映射循环引用
21、Gson Advanced - 泛型
22、Gson Advanced - 简单自定义序列化 (Part 1)
24、Gson Advanced - 自定义反序列化基础
25、Gson Advanced - 自定义对象实例创建
26、Gson Advanced - 通过 @JsonAdapter 自定义(反)序列化过程
32、Practical Gson - 如何解析多态对象

学习讨论

刚刚建了一个 Android 开源库分享学习群,有兴趣的小伙伴可以加入一起学习。

Practical Gson — 如何解析多态对象_第1张图片
群二维码

你可能感兴趣的:(Practical Gson — 如何解析多态对象)