Duplicate JSON Field with Jackson

后端 未结 3 480
孤独总比滥情好
孤独总比滥情好 2020-12-30 20:07

I am using Jackson for JSON (de)serialization in conjunction with Spring. However I am having an issue with a field being twice in some cases.

I have an abstract cla

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-30 20:34

    This behaviour is caused by the annotations placed on class AbstractBookmarkJsonModel:

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "mimeType")
    @JsonSubTypes({
        @JsonSubTypes.Type(value = ImageBookmarkJsonModel.class, name = "image/jpeg"),
        @JsonSubTypes.Type(value = EpubBookmarkJsonModel.class, name = "application/epub+zip")
    })
    

    @JsonTypeInfo tells Jackson to serialize the logical type name (JsonTypeInfo.Id.NAME) as a property (JsonTypeInfo.As.PROPERTY) with name mimeType (property = "mimeType"). With @JsonSubTypes.Type you assign the logical name application/epub+zip to EpubBookmarkJsonModel.

    When it comes to serialization, Jackson serializes the logical name as a property mimeType = "application/epub+zip" then the properties of the object among them mimeType which happens to have the same value as the logical name application/epub+zip (assigned in the constructor).

    I think mimeType should be changed to objectType in the @JsonTypeInfo annotation or even better to remove the mimeType field since Jackson will take care of that through type info serialization.

提交回复
热议问题