jackson ignore unknown properties with code examples

Jackson is one of the most popular and stable Java libraries used to work with JSON. This library provides several features to serialize and deserialize JSON data into Java objects without writing any boilerplate code. However, sometimes there can be cases where the JSON data has more properties than the expected Java class. Jackson provides a straightforward solution to handle these scenarios with the ignore unknown properties feature.

In this article, we'll explore how Jackson ignores unknown properties during deserialization and how to implement it in our Java code.

The Need for Ignore Unknown Properties

JSON data can vary in structure and size, so it's not uncommon to receive data from a source that has more properties than our Java class. For example, let's consider the following JSON data:

{
  "id": 234,
  "name": "John",
  "age": 25,
  "city": "New York",
  "country": "USA",
  "gender": "male"
}

However, what happens if our Java class only has the fields "id," "name," and "age"? Jackson will throw an exception because it can't map the properties "city," "country," and "gender" to any field in the Java class.

In such situations, we can either modify our Java class to include all the missing properties or specify which properties to ignore for deserialization.

By default, Jackson will throw the UnrecognizedPropertyException when it detects an unknown property during the deserialization process. But we can provide a way to ignore the unknown properties and allow the Jackson to map only the matching fields between JSON data and Java class.

Ignore Unknown Properties with @JsonIgnoreProperties

The @JsonIgnoreProperties annotation is the most convenient way to ignore unknown JSON properties during deserialization. We can add this annotation to our Java class definition or object mapper to ignore specific properties.

Let's look at a simple example that demonstrates how to ignore unknown JSON properties with @JsonIgnoreProperties.

@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    private String id;
    private String name;
    private int age;
    // getters and setters
}

Here, we added the @JsonIgnoreProperties(ignoreUnknown = true) annotation to our Person class. This tells Jackson to ignore any unknown properties in the JSON data while mapping the properties to the fields of our Java object. As a result, the gender and country properties in the JSON data will be ignored during deserialization.

Alternatively, we can also configure our object mapper to ignore unknown properties globally. The following code snippet shows how to configure the ObjectMapper instance to ignore unknown properties.

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Here, we used the configure method of the ObjectMapper instance, which allows us to set various properties and features for the Jackson library. We set the FAIL_ON_UNKNOWN_PROPERTIES feature to false, telling Jackson to ignore any unknown properties encountered while deserializing JSON data.

Ignore Unknown Properties with Custom Deserializer

Another way to ignore unknown properties is to create a custom deserializer. This approach is especially useful when we have a complex Java object and need to handle unknown properties using custom logic.

Let's say we have the following JSON data representing a job application:

{
  "jobTitle": "Software Engineer",
  "company": "Acme Inc",
  "yearsOfExperience": 4,
  "skills": ["Java", "Python", "C++"],
  "additionalFields": {
    "resume": "http://example.com/resume.pdf",
    "coverLetter": "http://example.com/cover_letter.pdf"
  }
}

Here, we have a "jobTitle," "company," "yearsOfExperience," and "skills" properties representing the required information in the job application. However, we also have an "additionalFields" property containing more data, such as a link to the applicant's resume and cover letter. We want to ignore this additionalFields property during deserialization.

We can create a custom deserializer to ignore specific JSON properties during the deserialization process. The following code snippet demonstrates how to create a custom deserializer to ignore the "additionalFields" property.

public class JobApplicationDeserializer extends JsonDeserializer<JobApplication> {

    @Override
    public JobApplication deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        JobApplication jobApplication = new JobApplication();

        JsonNode node = jsonParser.getCodec().readTree(jsonParser);

        if (node.has("jobTitle")) {
            jobApplication.setJobTitle(node.get("jobTitle").asText());
        }

        if (node.has("company")) {
            jobApplication.setCompany(node.get("company").asText());
        }

        if (node.has("yearsOfExperience")) {
            jobApplication.setYearsOfExperience(node.get("yearsOfExperience").asInt());
        }

        if (node.has("skills")) {
            List<String> skillsList = new ArrayList<>();
            JsonNode skills = node.get("skills");
            if (skills.isArray()) {
                for (JsonNode objNode : skills) {
                    skillsList.add(objNode.asText());
                }
            }
            jobApplication.setSkills(skillsList);
        }

        return jobApplication;
    }
}

Here, we created a custom deserializer for the JobApplication class that extends the JsonDeserializer class. We implemented the deserialize method, which maps the JSON data to the Java class fields.

We used the getCodec and readTree methods to read the entire JSON tree from the JsonParser and get the required properties from the JSON data using the has and get methods of the JsonNode object.

Notice that we didn't include the "additionalFields" property in the custom deserializer logic. As a result, Jackson will ignore the "additionalFields" property, and we can still map the required properties to our JobApplication class.

Conclusion

In this article, we explored how to ignore unknown properties in JSON data during deserialization with Jackson. We looked at two common approaches to ignoring unknown properties using the @JsonIgnoreProperties annotation and a custom deserializer.

By using these features, we can achieve flexible and robust JSON deserialization without worrying about unknown JSON properties.

let's dive a bit deeper into some of the topics covered in the previous article.

@JsonIgnoreProperties annotation

The @JsonIgnoreProperties annotation is a powerful tool that allows us to ignore unknown properties in JSON data during deserialization. This annotation can be added to the Java class definition or the object mapper instance to ignore specific properties.

The annotation has two parameters: value and ignoreUnknown. The "value" parameter is used to specify the names of the properties to ignore, while the "ignoreUnknown" parameter toggles the behavior of ignoring unknown properties.

Ignoring unknown properties can be useful in scenarios where the JSON data may contain additional information that our Java class doesn't need. By ignoring these properties, we can avoid unnecessary overhead and maintain the integrity of our application.

Custom Deserializer

A custom deserializer is a specialized Jackson class that provides a way to control how the JSON data is converted to the Java object. We use a custom deserializer when we need to perform custom logic to map the JSON data to the Java object.

The process of creating a custom deserializer involves creating a class that extends the JsonDeserializer class, implementing the deserialize method, and mapping the required properties manually.

Custom deserialization can be advantageous in situations where we need more control over the mapping process, such as parsing complex JSON data structures or handling errors during the mapping process.

ObjectMapper Configuration

The ObjectMapper is the primary class for working with Jackson in Java. It provides various methods and features that allow us to customize the behavior of the Jackson library.

One ObjectMapper feature is the ability to configure how the library handles unknown properties. By default, Jackson will throw an UnrecognizedPropertyException if it encounters an unknown property during deserialization. However, we can configure the ObjectMapper instance to ignore these errors and map only the known properties to the Java object.

We use the configure method of the ObjectMapper instance to set the desired configuration value. Setting DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES to false will tell Jackson to ignore unknown properties.

In summary, Jackson's ignore unknown properties feature is a useful tool that enables us to ignore unknown properties during JSON deserialization. We can leverage either the @JsonIgnoreProperties annotation, the custom deserializer, or ObjectMapper configuration to achieve this. By doing so, we can handle complex JSON data structures and maintain the integrity of our applications.

Popular questions

  1. What is Jackson and what is its purpose?
    Jackson is a Java library used to work with JSON data. Its purpose is to provide a straightforward solution to serialize and deserialize JSON data into Java objects without writing any boilerplate code.

  2. What happens when Jackson encounters unknown properties in the JSON data during deserialization?
    By default, Jackson will throw an UnrecognizedPropertyException if it encounters an unknown property during deserialization.

  3. How can we use the @JsonIgnoreProperties annotation to ignore unknown properties during deserialization?
    We can add the @JsonIgnoreProperties annotation to our Java class definition or object mapper to ignore specific properties. By setting the ignoreUnknown parameter to true, we can tell Jackson to ignore unknown properties during deserialization.

  4. When might we prefer to use a custom deserializer instead of the @JsonIgnoreProperties annotation?
    We may prefer to use a custom deserializer when we need more control over the mapping process, such as parsing complex JSON data structures or handling errors during the mapping process.

  5. How can we configure the ObjectMapper instance to ignore unknown properties during deserialization?
    We can configure the ObjectMapper instance to ignore unknown properties by setting the DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES configuration option to false. This tells Jackson to ignore any unknown properties encountered while deserializing JSON data.

Tag

Category: Relaxing

Example code:

const json = '{"name": "John", "age": 30, "gender": "male"}';
const object = JSON.parse(json, (key, value) => {
  if (key === 'name' || key === 'age') {
    return value;
  }
});

console.log(object); // { name: 'John', age: 30 }
As a senior DevOps Engineer, I possess extensive experience in cloud-native technologies. With my knowledge of the latest DevOps tools and technologies, I can assist your organization in growing and thriving. I am passionate about learning about modern technologies on a daily basis. My area of expertise includes, but is not limited to, Linux, Solaris, and Windows Servers, as well as Docker, K8s (AKS), Jenkins, Azure DevOps, AWS, Azure, Git, GitHub, Terraform, Ansible, Prometheus, Grafana, and Bash.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top