/ Java  

How to deserialize Json content with unknown property when using Jackson

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
2
3
4
5
{
"name": "name1",
"studentId": "12345",
"major": "computer science"
}

And the Java object:

1
2
3
4
5
6
class Student {
String name;
int studentId;

// getters and setters
}

When we map the Json to the Java object, will see the following exception:

1
2
3
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: 
Unrecognized field "major" (class com.experiment.jackson.JacksonDeserialize$Student),
not marked as ignorable (2 known properties: "name", "studentId"])

There are 2 ways to deal with this problem:

  1. Configure the ObjectMapper to ignore unknown properties

    1
    2
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  2. 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
    7
    @JsonIgnoreProperties (ignoreUnknown = true)
    class Student {
    String name;
    int studentId;

    // getters and setters
    }