When using Jackson to deserialize a Json string, if the Java object does’t include all the fields in the Json, Jackson will complain about unknown properties. In this post I will show how to ignore the properties if it is not defined in our Java object.
Suppose we have the following Json string:
1 | { |
And the Java object:
1 | class Student { |
When we map the Json to the Java object, will see the following exception:
1 | com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: |
There are 2 ways to deal with this problem:
Configure the ObjectMapper to ignore unknown properties
1
2ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);Mark the Java object to ignore unknown field. This way we only specify to ignore unknown properties when deserialize this particular class.
1
2
3
4
5
6
7true) (ignoreUnknown =
class Student {
String name;
int studentId;
// getters and setters
}