Java: Jackson polymorphic JSON deserialization of an object with an interface property? -


i using jackson's objectmapper deserialize json representation of object contains interface 1 of properties. simplified version of code can seen here:

https://gist.github.com/sscovil/8735923

basically, have class asset 2 properties: type , properties. json model looks this:

{     "type": "document",     "properties": {         "source": "foo",         "proxy": "bar"     } } 

the properties property defined interface called assetproperties, , have several classes implement (e.g. documentassetproperties, imageassetproperties). idea image files have different properties (height, width) document files, etc.

i've worked off of examples in this article, read through docs , questions here on , beyond, , experimented different configurations in @jsontypeinfo annotation parameters, haven't been able crack nut. appreciated.

most recently, exception i'm getting this:

java.lang.assertionerror: not deserialize json. ... caused by: org.codehaus.jackson.map.jsonmappingexception: not resolve type id 'source' subtype of [simple type, class assetproperties] 

thanks in advance!

solution:

with many @michaƂ ziober, able resolve issue. able use enum type id, took bit of googling. here updated gist working code:

https://gist.github.com/sscovil/8788339

you should use jsontypeinfo.as.external_property instead of jsontypeinfo.as.property. in scenario asset class should this:

class asset {      @jsontypeinfo(             use = jsontypeinfo.id.name,             include = jsontypeinfo.as.external_property,             property = "type")     @jsonsubtypes({         @jsonsubtypes.type(value = imageassetproperties.class, name = "image"),         @jsonsubtypes.type(value = documentassetproperties.class, name = "document") })     private assetproperties properties;      public assetproperties getproperties() {         return properties;     }      public void setproperties(assetproperties properties) {         this.properties = properties;     }      @override     public string tostring() {         return "asset [properties("+properties.getclass().getsimplename()+")=" + properties + "]";     } } 

see answer in question: jackson jsontypeinfo.as.external_property doesn't work expected.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -