Jackson serialization includes subclass's fields

瘦欲@ 提交于 2019-12-13 04:56:06

问题


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);

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


回答1:


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.



来源:https://stackoverflow.com/questions/25276479/jackson-serialization-includes-subclasss-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!