Ignore missing properties during Jackson JSON deserialization in Java

Viewed 123122

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?

7 Answers

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.

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;
}

if you annotate age with @JsonProperty(access = JsonProperty.Access.READ_ONLY) it will be ignored during deserialization only.

In Deserialization, two things may happen.

we have a new field in JSON String, not in Java Bean, that will be an unknown property for the object mapper. To ignore the unknown property, the object mapper configuration needs to be configured as below

ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

If a field is not in JSON String but in Java Bean, then that field will be treated as a missing property by the object mapper. To not fail on missing property, the object mapper configuration needs to be configured as below but this is the default behavior of Modern versions (2.9.6) of Jackson libraries.

ObjectMapper().configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false)

Related