杰克逊序列化包括子类的字段 [英] Jackson serialization includes subclass's fields

查看:146
本文介绍了杰克逊序列化包括子类的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Jackson序列化对象时遇到问题。文件中缺少子类中的字段。我试过Gson但也有同样的问题。谁能帮我这个?谢谢。

I had a problem when using Jackson to serialize an object. The fields in the subclass are missing in the file. I tried Gson but have the same problem as well. Can anyone help me with this? Thank you.

public class A extends ArrayList<B>{

    public String name;

    public A(){
    }
    //getter and setter
}

A a = new A();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(file, a);

文件包含B中的所有字段,但不包含A中的字段。

file includes all the fields in B, but it does not contains fields in A.

推荐答案

通过使自定义类型为 List 子类型,Jackson使用特殊的列出生成JSON的特定序列化程序。它将简单地迭代 List 的元素并编写它们。

By making your custom type a List subtype, Jackson uses a special List specific serializer to generate the JSON. It will simply iterate the elements of the List and write those.

不使用继承,而是使用合成。

Instead of using inheritance, use composition.

这篇关于杰克逊序列化包括子类的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆