Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring new fields on JSON objects using Jackson [duplicate]

Tags:

java

json

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.

like image 953
Hadi Eskandari Avatar asked Mar 28 '11 05:03

Hadi Eskandari


People also ask

How do you ignore a field in JSON response?

The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.

How do I ignore unknown properties on Jackson?

Jackson API provides two ways to ignore unknown fields, first at the class level using @JsonIgnoreProperties annotation and second at the ObjectMapper level using configure() method.

How do I ignore JSON property if null?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

What is Fail_on_unknown_properties?

FAIL_ON_UNKNOWN_PROPERTIES. Feature that determines whether encountering of unknown properties (ones that do not map to a property, and there is no "any setter" or handler that can handle it) should result in a failure (by throwing a JsonMappingException ) or not.


1 Answers

Jackson provides an annotation that can be used on class level (JsonIgnoreProperties).

Add the following to the top of your class (not to individual methods):

@JsonIgnoreProperties(ignoreUnknown = true) public class Foo {     ... } 

Depending on the jackson version you are using you would have to use a different import in the current version it is:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 

in older versions it has been:

import org.codehaus.jackson.annotate.JsonIgnoreProperties; 
like image 72
Hadi Eskandari Avatar answered Oct 12 '22 01:10

Hadi Eskandari