Search code examples
javajsonserializationjackson

Ignore missing properties during Jackson JSON deserialization in Java


In the example

class Person {
   String name;
   int age;
}

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

{
    "name": "John"
}
Person person = objectMapper.readValue(jsonFileReader, Person.class);

it throws a JsonMappingException saying it cannot deserialize. Is there an annotation to ignore missing fields during deserialization?


Solution

  • 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.