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:

  1. om.enabledefaulttyping() store class name elements stored object or abstract types (including interfaces). see documentation overloads. work collections automatically.

  2. 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 store list<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

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -