json - Serialzing heterogeneous collection with Jackson in Java -
i'm using jackson serialize heterogeneous list. list declared this:
list<base> mylist = new linkedlist<>();
i have classes aggregate
, source
in there:
mylist.add(new aggregate("count")); mylist.add(new aggregate("group")); mylist.add(new source("reader"));
those classes both implement base
interface. each class has single property get/set method: aggregate
has "type", , source
has "name".
i use code try serialize list:
objectmapper om = new objectmapper(); om.configure(serializationfeature.indent_output, true); stringwriter c = new stringwriter(); om.writevalue(c, mylist); system.out.println(c);
but find output json doesn't have indication of type of object serialized:
[ { "type" : "count" }, { "type" : "group" }, { "name" : "reader" } ]
as such, don't think can possibly de-serialize stream , have work expect. how can include class information on serialized representation of each object in heterogeneous collection such collection can correctly de-serialized?
this described in http://wiki.fasterxml.com/jacksonpolymorphicdeserialization. read it, here relevant parts.
to include type information elements, see section 1. there 2 alternatives:
om.enabledefaulttyping()
store class name elements storedobject
or abstract types (including interfaces). see documentation overloads. work collections automatically.annotate
base
@jsontypeinfo
(e.g.@jsontypeinfo(use=jsontypeinfo.id.class, include=jsontypeinfo.as.property, property="@class")
). make work collections, you'll need tell jackson want storelist<base>
(and see section 5):om.writerwithtype(new typereference<list<base>>() {}).writevalue(...);
or
javatype listbase = objectmapper.constructcollectiontype(list.class, base.class); om.writerwithtype(listbase).writevalue(...);
Comments
Post a Comment