java - How to de/serialize an immutable object without default constructor using ObjectMapper? -
i want serialize , deserialize immutable object using com.fasterxml.jackson.databind.objectmapper.
the immutable class looks (just 3 internal attributes, getters , constructors):
public final class importresultitemimpl implements importresultitem { private final importresultitemtype resulttype; private final string message; private final string name; public importresultitemimpl(string name, importresultitemtype resulttype, string message) { super(); this.resulttype = resulttype; this.message = message; this.name = name; } public importresultitemimpl(string name, importresultitemtype resulttype) { super(); this.resulttype = resulttype; this.name = name; this.message = null; } @override public importresultitemtype getresulttype() { return this.resulttype; } @override public string getmessage() { return this.message; } @override public string getname() { return this.name; } }
however when run unit test:
@test public void testobjectmapper() throws exception { importresultitemimpl originalitem = new importresultitemimpl("name1", importresultitemtype.success); string serialized = new objectmapper().writevalueasstring((importresultitemimpl) originalitem); system.out.println("serialized: " + serialized); //this line throw exception importresultitemimpl deserialized = new objectmapper().readvalue(serialized, importresultitemimpl.class); }
i exception:
com.fasterxml.jackson.databind.jsonmappingexception: no suitable constructor found type [simple type, class eu.ibacz.pdkd.core.service.importcommon.importresultitemimpl]: can not instantiate json object (missing default constructor or creator, or perhaps need add/enable type information?) @ [source: {"resulttype":"success","message":null,"name":"name1"}; line: 1, column: 2] @ ... nothing interesting here
this exception asks me create default constructor, immutable object, don't want have it. how set internal attributes? totally confuse user of api.
so question is: can somehow de/serialize immutable objects without default constructor?
to let jackson know how create object deserialization, use @jsoncreator
, @jsonproperty
annotations constructors, this:
@jsoncreator public importresultitemimpl(@jsonproperty("name") string name, @jsonproperty("resulttype") importresultitemtype resulttype, @jsonproperty("message") string message) { super(); this.resulttype = resulttype; this.message = message; this.name = name; }
Comments
Post a Comment