Java Jackson : Can I hold in a json the type to deserialize it to? -
the usual way serialize json , is:
string catstr = mapper.writevalueasstring(cat); cat catout = mapper.readvalue(catstr, cat.class);
is there way add (maybe annotation ) type json on serialization , let mapper take value when deserialize it?
so can following
object obj = mapper.readvalue(catstr);
and later...
cat catout = (cat)obj;
thanks.
sort of. can add property serialization indicate class is. , when deserializing it, jackson deduces class automatically.
but cannot deserialize object, need base class/interface objects want behave this. , interface needs use @jsontypeinfo
annotation, signalling jackson when deserializing base class use property class distinguish type.
example:
@jsontypeinfo(use = jsontypeinfo.id.class, include = jsontypeinfo.as.property) private abstract class base { } private class extends base { private final int i; @jsoncreator public a(@jsonproperty("i") int i) { this.i = i; } }
when serialized be:
{"@class":"com.test.a","i":3}
testing code:
a = new a(3); string str = mapper.writevalueasstring(a); base base = mapper.readvalue(str, base.class);
Comments
Post a Comment