What's the Jackson deserialization equivalent of @JsonUnwrapped?

后端 未结 4 1173
天命终不由人
天命终不由人 2020-12-01 13:43

Say I have the following class:

public class Parent {
  public int age;
  @JsonUnwrapped
  public Name name;
}

Producing JSON:



        
相关标签:
4条回答
  • 2020-12-01 14:03

    You can use @JsonCreator with @JsonProperty for each field:

    @JsonCreator
    public Parent(@JsonProperty("age") Integer age, @JsonProperty("firstName") String firstName,
            @JsonProperty("lastName") String lastName) {
        this.age = age;
        this.name = new Name(firstName, lastName);
    }
    

    Jackson does type checking and unknown field checking for you in this case.

    0 讨论(0)
  • 2020-12-01 14:11

    @JsonUnwrapped works for both serialization and deserialization, you shouldn't need to take any additional steps.

    0 讨论(0)
  • 2020-12-01 14:15

    It does work for deserialization as well, although it's not mentioned in the docs explicitly, like you said. See the unit test for deserialization of @JsonUnwrapped here for confirmation - https://github.com/FasterXML/jackson-databind/blob/d2c083a6220f2875c97c29f4823d9818972511dc/src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java#L138

    0 讨论(0)
  • 2020-12-01 14:25

    For those who googled here like me, trying to resolve issue when deserializing unwrapepd Map, there is a solution with @JsonAnySetter:

    public class CountryList
    {
    
        Map<String, Country> countries = new HashMap<>();
    
        @JsonAnySetter
        public void setCountry(String key, Country value)
        {
            countries.put(key, value);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题