Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson polymorphic type handling - property discarded

Tags:

java

json

jackson

I have this JSON model class,

public class Response {

    @JsonTypeInfo(use= JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="category")
    @JsonSubTypes({
            @Type(value = Series.class, name = "Series"),
            @Type(value = Movies.class, name = "Movies")})
    public static abstract class Asset {
        public String category;
        public String id;
    }

    public static class Series extends Asset {
        public String seriesName;
        public int seasonNumber;
    }

    public static class Movies extends Asset {
        public String movieName;
    }

    public Asset[] assets;
}

When I try to deserialize the following JSON,

{
    assets: [
        {
            "category": "Series",
            "id": "ID1",
            "seriesName": "SeriesName1",
            "seasonNumber": 1
        },
        {
            "category": "Movies",
            "id": "ID2",
            "movieName": "MovieName1"
        }
    ]
}

I see that all the properties are deserialized properly, except the category property, which are null in both asset types.

Am I doing something wrong? Or is this the expected behavior - property that is used to infer subtype is discarded during deserialization?

like image 402
zihaoyu Avatar asked Feb 05 '13 21:02

zihaoyu


2 Answers

You need to set visible = true:

@JsonTypeInfo(
    use= JsonTypeInfo.Id.NAME,
    include=JsonTypeInfo.As.PROPERTY,
    property="category",
    visible = true
)
like image 189
vovkab Avatar answered Nov 02 '22 22:11

vovkab


Yes, the category property is used to determine the type of the returned object as declared in the annotation. If you still want to have that property in your deserialized objects you can add another property for type discrimination or write a deserialization without type element as in example 6 from this post.

like image 30
Bogdan Avatar answered Nov 02 '22 20:11

Bogdan