json - jackson serialization for Java object with Map? -


i have java class , want convert json using jackson. help.

  1. java class

    public class myclass {    string id;    map<string, object> optionaldata = new linkedhashmap<string, object>(); } 
  2. how serialization json using jackson objectmapper ?

for example, suppose optionaldata map saving 2 entries <"type", "book"> , <"year", "2014"> want output follow. please note key/value of optionaldata changed on fly (so, cannot create "static" java object without using map)

  [      {        id: "book-id1",       type: "book",       year: "2014"     },     {        id: "book-id2",       type: "book",       year: "2013"      }   ] 

you need write own jackson jsonserializer create custom json string java object per need.

here nice posts along example


the same thing can achieve using gson jsonserializer

here examples


here code using gson serialiser

list<myclass> list = new arraylist<myclass>();  myclass myclass1 = new myclass(); myclass1.setid("book-id1"); myclass1.getoptionaldata().put("type", "book"); myclass1.getoptionaldata().put("year", "2014"); list.add(myclass1);  myclass myclass2 = new myclass(); myclass2.setid("book-id2"); myclass2.getoptionaldata().put("type", "book"); myclass2.getoptionaldata().put("year", "2013"); list.add(myclass2);  class myclassserialiser implements jsonserializer<myclass> {      @override     public jsonelement serialize(final myclass obj, final type typeofsrc,             final jsonserializationcontext context) {         final jsonobject jsonobject = new jsonobject();          jsonobject.addproperty("id", obj.getid());         map<string, string> optioanldata = obj.getoptionaldata();         if (optioanldata.size() > 0) {             (map.entry<string, string> entry : optioanldata.entryset()) {                 jsonobject.addproperty(entry.getkey(), entry.getvalue());             }         }          return jsonobject;     } }  string jsonstring = new gsonbuilder().setprettyprinting().         .registertypeadapter(myclass.class, new myclassserialiser()).create()         .tojson(list);  system.out.println(jsonstring); 

output:

[     {         "id": "book-id1",         "type": "book",         "year": "2014"     },     {         "id": "book-id2",         "type": "book",         "year": "2013"     } ] 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -