8

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?

zihaoyu
  • 5,483
  • 11
  • 42
  • 46
  • do you have also control on serialization? I mean if you can add other properties into the json stream – eugen Feb 05 '13 at 22:09
  • @eugen I do not have control over serialization. I think adding a type discriminator in sub types is the easier way to go. – zihaoyu Feb 05 '13 at 22:19

2 Answers2

22

You need to set visible = true:

@JsonTypeInfo(
    use= JsonTypeInfo.Id.NAME,
    include=JsonTypeInfo.As.PROPERTY,
    property="category",
    visible = true
)
vovkab
  • 1,292
  • 11
  • 17
  • Exactly what I needed, I have an enum that is needed in my POJO, but it would be set to null after the subtype was selected. Setting visible=true keeps its original value. – Limnic Oct 26 '17 at 10:15
  • I would assume should be visible=true by default, why not?! Thanks for answer – Dmitri Algazin Nov 27 '17 at 17:54
2

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.

Bogdan
  • 934
  • 7
  • 13
  • Thanks, I think adding a type discriminator in sub types is the easier way to go. – zihaoyu Feb 05 '13 at 22:20
  • 1
    But why do you want that property? Jackson already adds 'category' in JSON, and unless you have specific additional need, you do not need a POJO property of that name. – StaxMan Feb 06 '13 at 04:51