java - Jackson map different attributes based on json in the same class -
i have class response
has attribute data
.
a json file mapped object. data
attribute can of type taskdata
or submitdata
on json.
if json has object of type taskdata
object mapper must map taskdata
class or should map `submitdata' class.
you need type response
class follows: public class response<t>
.
then, when deserializing input, provide typereference
jackson indicate desired type.
see example:
import java.io.ioexception; import java.io.stringreader; import java.io.stringwriter; import com.fasterxml.jackson.core.jsongenerationexception; import com.fasterxml.jackson.core.type.typereference; import com.fasterxml.jackson.databind.jsonmappingexception; import com.fasterxml.jackson.databind.objectmapper; public class testjacksontyping { public static void main(string[] args) throws jsongenerationexception, jsonmappingexception, ioexception { objectmapper mapper = new objectmapper(); response<taskdata> taskresponse = new response<taskdata>(); taskdata taskdata = new taskdata(); taskdata.settasktitle("some title"); taskresponse.setdata(taskdata); response<submitdata> submitresponse = new response<submitdata>(); submitdata submitdata = new submitdata(); submitdata.setsubmitvalue(256); submitresponse.setdata(submitdata); stringwriter sw = new stringwriter(); mapper.writevalue(sw, taskresponse); string taskresponsejson = sw.tostring(); mapper.writevalue(sw = new stringwriter(), submitresponse); string submitresponsejson = sw.tostring(); response<taskdata> deserializedtaskresponse = mapper.reader(new typereference<response<taskdata>>() { }).readvalue(new stringreader(taskresponsejson)); response<submitdata> deserializedsubmitresponse = mapper.reader(new typereference<response<submitdata>>() { }).readvalue(new stringreader(submitresponsejson)); system.out.println(deserializedtaskresponse.getdata().gettasktitle()); system.out.println(deserializedsubmitresponse.getdata().getsubmitvalue()); } public static class response<t> { private t data; public t getdata() { return data; } public void setdata(t data) { this.data = data; } } public static class taskdata { private string tasktitle; public string gettasktitle() { return tasktitle; } public void settasktitle(string tasktitle) { this.tasktitle = tasktitle; } } public static class submitdata { private int submitvalue; public int getsubmitvalue() { return submitvalue; } public void setsubmitvalue(int submitvalue) { this.submitvalue = submitvalue; } } }