java - Calling custom JsonDeserializer from another JsonDeserializer -
i'm trying invoke custom jsondeserializer one, can't figure out how.
i'm using @jsondeserialize annotations in entities:
@jsondeserialize(using = bobdeserializer.class) class bob { private integer number; ... } @jsondeserialize(using = alicedeserializer.class) class alice { private bob bob; ... }
my deserializers are:
class bobdeserializer extends stddeserializer<bob> { public bob deserialize(jsonparser parser, deserializationcontext context) throws ioexception { jsonnode node = parser.getcodec().readtree(parser); integer number = node.get("number").asint(); bob bob = new bob(); bob.setnumber(number); return bob; } } class alicedeserializer extends stddeserializer<alice> { public alice deserialize(jsonparser parser, deserializationcontext context) throws ioexception { jsonnode node = parser.getcodec().readtree(parser); bob bob = ???????; // how bob calling bobdeserializer deserialize node.get("bob")? alice alice = new alice(); alice.setbob(bob); return alice; } }
alicedeserializer receives json input following:
{ "bob": { "number": 2 } }
i need invoking bobdeserializer alicedeserializer. i want use automatic mechanism this, instead of injecting deserializer using @autowired.
thank you
in general, when writing custom deserializer need make sure can serialize objectmapper
instead of parsing every field itself. once that, objectmapper
automatically call deserializer of object if exists.
and code:
@jsondeserialize(using = bobdeserializer.class) class bob { private integer number; public bob() { } public integer getnumber() { return number; } public void setnumber(integer number) { this.number = number; } } @jsondeserialize(using = alicedeserializer.class) public class alice { private bob bob; public alice() { } public bob getbob() { return bob; } public void setbob(bob bob) { this.bob = bob; } } class bobdeserializer extends stddeserializer<bob> { protected bobdeserializer() { super(bob.class); } public bob deserialize(jsonparser parser, deserializationcontext context) throws ioexception { jsonnode node = parser.getcodec().readtree(parser); integer number = node.get("number").asint(); bob bob = new bob(); bob.setnumber(number); return bob; } } class alicedeserializer extends stddeserializer<alice> { protected alicedeserializer() { super(alice.class); } public alice deserialize(jsonparser parser, deserializationcontext context) throws ioexception { jsonnode node = parser.getcodec().readtree(parser); objectmapper mapper = new objectmapper(); bob bob = mapper.readvalue(node.get("bob").tostring(), bob.class); alice alice = new alice(); alice.setbob(bob); return alice; } }
and deserializing test code:
alice alice = new alice(); bob bob = new bob(); bob.setnumber(3); alice.setbob(bob); objectmapper mapper = new objectmapper(); alice alice1 = mapper.readvalue(mapper.writevalueasstring(alice), alice.class);
Comments
Post a Comment