java - Deserialize JSON by property -


i have simple wrapper class.

class wrapper {     int id;     object command; } 

command object outside, , cannot create interface hold possible types together. i'd serialize simply:

string json = objectmapper.writevalueasstring(wrapper); 

so get:

{"id":"1","command":{"type" : "objecttype", "key0": "val0", ... other properties...}} 

ideally i'd build registry possible values of type , corresponding class names values, deserialize this:

wrapper wrapper = objectmapper.readvalue(bytes, wrapper.class); 

(objectmapper com.fasterxml.jackson.databind.objectmapper)

is there way achieve jackson?

you can use the jackson polymorphic type handling. can declare type command property can using @jsontypexxx annotations.

here complete example:

public class jacksontypeinfoonobject {      public static class bean {         @jsontypeinfo(use = jsontypeinfo.id.name, property = "type")         @jsonsubtypes({                 @jsonsubtypes.type(command1.class),                 @jsonsubtypes.type(command2.class)         })         public final object command;          @jsoncreator         public bean(@jsonproperty("command") final object command) {this.command = command;}          @override         public string tostring() {             return "bean{" +                     "command=" + command +                     '}';         }     }      @jsontypename("cmd1")     public static class command1 {         @override         public string tostring() {             return "command1{}";         }     }      @jsontypename("cmd2")     public static class command2 {         @override         public string tostring() {             return "command2{}";         }     }       public static void main(string[] args) throws ioexception {         final objectmapper mapper = new objectmapper();         mapper.disable(serializationfeature.fail_on_empty_beans);         final list<bean> list = arrays.aslist(                 new bean(new command1()),                 new bean(new command2()));         final string json = mapper.writevalueasstring(list);         system.out.println(json);         final list<bean> values = mapper.readvalue(json, new typereference<list<bean>>() {});         system.out.println(values);     } } 

output:

[{"command":{"type":"cmd1"}},{"command":{"type":"cmd2"}}] [bean{command=command1{}}, bean{command=command2{}}] 

Comments