java - Custom Json Deserializer in Jackson for Hashmap only -


i'm writing json serialization (using jackson) hierarchy of java classes, i.e. classes composed of other classes. since, i'm not serializing properties, i've used jsonviews , have annotated properties want serialize. class @ top of hierarchy contains map needs serialized/deserialized. possible write serializer/deserializer map ? want default serializer take care of serializing rest of objects

why requirement ? if define serializer topmost class, need serialization objects. jsongenerator object seems ignore jsonview annotations , serializes properties.

sure possible. define custom serializer map class generic type, bind using jackson module subsystem.

here example: (it produces silly custom serialization, principal valid)

public class test {     // "topmost" class     public static class dto {         public string name = "name";         public boolean b = false;          public int = 100;          @jsonview(myview.class)         public map<string, string> map; {             map = new hashmap<>();             map.put("key1", "value1");             map.put("key2", "value2");             map.put("key3", "value3");         }     }      // prove works views...     public static class myview {}      // custom serializer map      public static class mapserializer extends jsonserializer<map> {         @override         public void serialize(map map, jsongenerator gen, serializerprovider serializers) throws ioexception, jsonprocessingexception {             // custom serialization goes here ....             gen.writestartobject();             gen.writefieldname("map-keys");             gen.writestartarray();             gen.writestring(map.keyset().tostring());             gen.writeendarray();             gen.writefieldname("map-valuess");             gen.writestartarray();             gen.writestring(map.values().tostring());             gen.writeendarray();             gen.writeendobject();         }     }      public static void main(string[] args) {         simplemodule module = new simplemodule();         module.addserializer(map.class, new mapserializer());         objectmapper mapper = new objectmapper();         mapper.disable(mapperfeature.default_view_inclusion);         mapper.registermodule(module);         try {             mapper.writerwithview(myview.class).writevalue(system.out, new dto());         } catch (exception e) {             e.printstacktrace();         }     } } 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -