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

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -