Java Jackson JSON Ignore Unknown Fields

1. Introduction

When working with JSON data using the Jackson library in Java, there might be instances where the JSON source contains fields that do not map to any property in the target Java object. By default, Jackson throws an exception if it encounters an unknown property during deserialization. However, there are situations where we want to simply ignore such properties and continue with the deserialization process. In this post, we'll demonstrate how to configure Jackson to ignore unknown JSON properties.

2. Program Steps

1. Set up your Java project with the required Jackson dependency.

2. Create a Java POJO (Plain Old Java Object) that represents the data structure.

3. Use Jackson's ObjectMapper class to deserialize the JSON content, configuring it to ignore unknown fields.

4. Display the deserialized Java object.

3. Code Program

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonJsonIgnoreUnknownExample {

    public static class Person {
        public String name;
        public int age;

        @Override
        public String toString() {
            return "Person{name='" + name + "', age=" + age + "}";
        }
    }

    public static void main(String[] args) {
        try {
            // Sample JSON content with an extra 'gender' field
            String jsonString = "{\"name\":\"John\", \"age\":30, \"gender\":\"male\"}";

            // Create ObjectMapper instance
            ObjectMapper objectMapper = new ObjectMapper();
            // Configure ObjectMapper to ignore unknown properties
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            // Deserialize JSON string to Person object
            Person person = objectMapper.readValue(jsonString, Person.class);

            System.out.println(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Person{name='John', age=30}

4. Step By Step Explanation

1. The sample JSON string represents a person with attributes: name, age, and an extra attribute gender which doesn't exist in our Person class.

2. By default, if we try to deserialize this JSON, Jackson would throw an exception due to the unrecognized 'gender' field.

3. To prevent this, we configure our ObjectMapper instance by setting the FAIL_ON_UNKNOWN_PROPERTIES feature to false. This tells Jackson to ignore any unknown properties rather than fail.

4. We then use the readValue method of ObjectMapper to deserialize the JSON string to a Person object.

5. The resulting Person object only has values for the recognized fields (name and age). The gender field from the JSON string is simply ignored during deserialization.

By configuring the ObjectMapper as shown, we can effortlessly handle JSON data with additional or unknown fields without causing any errors or exceptions.


Comments