While working with JSON formats in Java, we often get UnrecognizedPropertyException: Unrecognized field not marked as ignorable, while trying to map JSON fields to a Java object. This usually means that we didn’t declare a property in our Java object that corresponds to the field in the JSON object.
If we try to convert a JSON object into a Java object, we must declare all fields in our Java POJO, to match the fields inside the JSON object.
For example, if we have the following JSON message:
{ "firstName" : "John", "lastName": "Doe", "gender": "Male", "state": "Texas" }
And the following Person.class:
public class Person { private String firstName; private String lastName; private String state; // constructors, getters and setters }
Now, if we try to convert the above JSON into the Person object, we’ll get the UnrecognizedPropertyException, since we didn’t declare the gender field.
Fix the “UnrecognizedPropertyException: Unrecognized field not marked as ignorable”
There are a few possible fixes that we can use for the above error, depending on the use case. These are:
- By declaring/adding the missing field in POJO
- Using the @JsonIgnoreProperties annotation
- By configuring the ObjectMapper
- Using the @JsonProperty annotation
Declaring/adding the missing field in POJO
We can just add the missing field into our Person class:
public class Person { private String firstName; private String lastName; private String gender; <<<< private String state; }
Using the @JsonIgnoreProperties annotation
There is a class-level annotation that we can use to instruct Jackson to ignore any missing field. Just put the following above the class declaration: @JsonIgnoreProperties(ignoreUnknown = true)
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Person { // ... }
Configuring the ObjectMapper to ignore the fields not marked as ignorable
The third way is to configure the ObjectMapper instance not to fail when we have unknown properties:
// creating an instance of the ObjectMapper private ObjectMapper mapper = new ObjectMapper(); // configuring the objectMapper to ignore the error in case we have some unrecognized fields mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
Using the @JsonProperty annotation
We can also use the @JsonProperty annotation in cases when we did declare the field, but we named it differently compared to the field inside JSON.
public class Person { private String firstName; private String lastName; @JsonProperty("gender") private String maleOrFemale; private String state; }
With this, Jackson will map the field gender from the JSON to the maleOrFemale field in our POJO.
And that’s it! This tutorial is part of the Java JSON tutorial.
Happy coding!