How to deserialize extra properties of json document into a map or other field with jackson?

为君一笑 提交于 2021-01-28 06:09:40

问题


I have a class/interface pair defined like this in Kotlin:

@JsonDeserialize(`as` = SimpleEvent::class)
interface Event {
    val organizationId: UUID
    val userId: UUID
    val eventTime: LocalDateTime
    val eventId: UUID
    @get:JsonAnyGetter
    @get:JsonAnySetter
    val details: Map<String, JsonNode>
}

data class SimpleEvent(
    override val organizationId: UUID,
    override val userId: UUID,
    override val eventTime: LocalDateTime,
    override val eventId: UUID,
    override val details: Map<String, JsonNode>
) : Event

My goal is to turn any extra fields from the json document as entries in the details map. The @JsonAnyGetter and @JsonAnySetter annotations are promising, but I can't find a way to make @JsonAnySetter work with immutable constructor parameters. @JsonAnyGetter works as intended, but @JsonAndSetter appears to be ignored.


回答1:


As workaround, this works:

@JsonAnySetter
@get:JsonAnyGetter
        val others:Map<String,JsonNode> = LinkedHashMap()  /* workaround!*/



回答2:


Use @JsonAnySetter on a mutable property. It is not yet supported for constructor parameters, although there is a request to add that:

https://github.com/FasterXML/jackson-databind/issues/562


来源:https://stackoverflow.com/questions/50750036/how-to-deserialize-extra-properties-of-json-document-into-a-map-or-other-field-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!