Ignore missing properties during Jackson JSON deserialization in Java

前端 未结 6 1441
时光说笑
时光说笑 2020-12-03 06:14

In the example

class Person {
   String name;
   int age;
}

If the JSON object has a missing property \'age\',

{
  name :          


        
相关标签:
6条回答
  • 2020-12-03 07:02

    Modern versions (2.9.6) of Jackson libraries will ignore missing creator properties by default. However, if the ObjectMapper configuration is set to:

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true);
    

    Then you'll get a deserialization error if one of the properties is missing.

    0 讨论(0)
  • 2020-12-03 07:02

    I think you would want to use the @JsonIgnore annotation: https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonIgnore.html

    0 讨论(0)
  • 2020-12-03 07:04

    You could also change your class to use an Integer instead of an int, in which case Jackson will handle null/missing "age" values properly. Just adding this answer for those looking for an alternative that doesn't involve using annotations.

    class Person {
       String name;
       Integer age;
    }
    
    0 讨论(0)
  • 2020-12-03 07:05

    @JsonIgnoreProperties(ignoreUnknown = true) on the class level worked for me.

    0 讨论(0)
  • 2020-12-03 07:11

    I think what you want is

    @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
    public class Person {
      ...
    }
    

    that's the Jackson 1.x way. I think there's a new way in 2.x. Something like

    @JsonInclude(Include.NON_NULL)
    public class Person {
      ...
    }
    

    These will tell Jackson to only serialize values that are not null, and don't complain when deserializing a missing value. I think it will just set it to the Java default.

    0 讨论(0)
  • 2020-12-03 07:13

    Annotation based approach is a better way for ignoring but If needed. The manual way of deserialization:

    ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Person       person = mapper.readValue(jsonFileReader, Person.class);
    
    0 讨论(0)
提交回复
热议问题