[java] Ignoring new fields on JSON objects using Jackson

I'm using Jackson JSON library to convert some JSON objects to POJO classes on an android application. The problem is, the JSON objects might change and have new fields added while the application is published, but currently it will break even when a simple String field is added, which can safely be ignored.

Is there any way to tell Jackson to ignore newly added fields? (e.g. non-existing on the POJO objects)? A global ignore would be great.

This question is related to java json jackson

The answer is


You can annotate the specific property in your POJO with @JsonIgnore.


it can be achieved 2 ways:

  1. Mark the POJO to ignore unknown properties

    @JsonIgnoreProperties(ignoreUnknown = true)
    
  2. Configure ObjectMapper that serializes/De-serializes the POJO/json as below:

    ObjectMapper mapper =new ObjectMapper();            
    // for Jackson version 1.X        
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // for Jackson version 2.X
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) 
    

@JsonIgnoreProperties(ignoreUnknown = true) worked well for me. I have a java application which runs on tomcat with jdk 1.7.


Up to date and complete answer with Jackson 2


Using Annotation

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyMappingClass {

}

See JsonIgnoreProperties on Jackson online documentation.

Using Configuration

Less intrusive than annotation.

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

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

ObjectReader objectReader = objectMapper.reader(MyMappingClass.class);
MyMappingClass myMappingClass = objectReader.readValue(json);

See FAIL_ON_UNKNOWN_PROPERTIES on Jackson online documentation.


I'm using jackson-xxx 2.8.5.Maven Dependency like:

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.5</version>
    </dependency>

</dependencies>

First,If you want ignore unknown properties globally.you can config ObjectMapper.
Like below:

ObjectMapper objectMapper = new ObjectMapper();

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

If you want ignore some class,you can add annotation @JsonIgnoreProperties(ignoreUnknown = true) on your class like:

@JsonIgnoreProperties(ignoreUnknown = true)
public class E1 {

    private String t1;

    public String getT1() {
        return t1;
    }

    public void setT1(String t1) {
        this.t1 = t1;
    }
}

For whom are using Spring Boot, you can configure the default behaviour of Jackson by using the Jackson2ObjectMapperBuilder.

For example :

@Bean
public Jackson2ObjectMapperBuilder configureObjectMapper() {
    Jackson2ObjectMapperBuilder oMapper = new Jackson2ObjectMapperBuilder();
    oMapper.failOnUnknownProperties(false);
    return oMapper;
}

Then you can autowire the ObjectMapper everywhere you need it (by default, this object mapper will also be used for http content conversion).


Make sure that you place the @JsonIgnoreProperties(ignoreUnknown = true) annotation to the parent POJO class which you want to populate as a result of parsing the JSON response and not the class where the conversion from JSON to Java Object is taking place.


As stated above the annotations only works if this is specified in the parent POJO class and not the class where the conversion from JSON to Java Object is taking place.

The other alternative without touching the parent class and causing disruptions is to implement your own mapper config only for the mapper methods you need for this.

Also the package of the Deserialization feature has been moved. DeserializationConfig.FAIL_ON_UNKNOWN_PROPERTIES to DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES

import org.codehaus.jackson.map.DeserializationConfig;
...
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

If using a pojo class based on JSON response. If chances are there that json changes frequently declare at pojo class level:

@JsonIgnoreProperties(ignoreUnknown = true)

and at the objectMapper add this if you are converting:

objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

So that code will not break.


In addition to 2 mechanisms already mentioned, there is also global feature that can be used to suppress all failures caused by unknown (unmapped) properties:

// jackson 1.9 and before
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// or jackson 2.0
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

This is the default used in absence of annotations, and can be convenient fallback.


Starting with Jackson version 2.4 and above there have been some changes. Here is how you do it now:

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

..........................................................................

 ObjectMapper mapper = new ObjectMapper();
    // to prevent exception when encountering unknown property:
 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

Note: The @annotation based solution remains the same so if you like to use that see the other answers.

For more information see the 10 minutes Configuration tutorial at: https://github.com/FasterXML/jackson-databind


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to jackson

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to convert JSON string into List of Java object? Deserialize Java 8 LocalDateTime with JacksonMapper java.lang.IllegalArgumentException: No converter found for return value of type java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value How to modify JsonNode in Java? Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error Convert Map to JSON using Jackson Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter