问题
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