How to deserialize interface fields using Jackson's objectMapper?

前端 未结 2 1244
名媛妹妹
名媛妹妹 2020-12-24 01:50

ObjectMapper\'s readValue(InputStream in, Class valueType) function requires the Class. But how do I use it if the class I am passing inte

相关标签:
2条回答
  • 2020-12-24 02:24

    I see it going one of two ways, but they both require you manually create a concrete class that implements your interface.

    1. Use @Hari Menon's answer and use @JsonSubTypes. This works if you can introduce a type field or something else to trigger which implementation to use.
    2. Use @JsonDeserialize to tell jackson what concrete class it uses by default.
    @JsonDeserialize(as = MVDImpl.class)
    interface MetricValueDescriptor
    {
       ...
    }
    

    Here's a more thorough explanation: https://zenidas.wordpress.com/recipes/jackson-deserialization-of-interfaces/

    And the docs: https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/annotation/JsonDeserialize.html

    0 讨论(0)
  • 2020-12-24 02:43

    Jackson obviously cannot construct the MetricValueDescriptor object since it is an interface. You will need to have additional information in your json and in your ObjectMapper to tell jackson how to construct an object out of it. Here is one way to do it, assuming MVDImpl is a concrete class which implements MetricValueDescriptor:

    You can tell Jackson the required type information through a field in the json itself, say "type". To do this, you need to use JsonTypeInfo and JsonSubTypes annotations in your interface. For example,

    @JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "type")
    @JsonSubTypes({
        @Type(value = MVDImpl.class, name = "mvdimpl") })
    interface MetricValueDescriptor
    {
       ...
    }
    

    You will need to add a "type":"mvdimpl" field in your json as well.

    I was going to point you to the official doc for more info, but then I found an excellent blog covering this topic - Deserialize JSON with Jackson. It covers this topic pretty comprehensively and with examples. So you should definitely read it if you need more customisation.

    0 讨论(0)
提交回复
热议问题