Jose M Lechon
Jose M Lechon

Reputation: 5896

Jackson crash when try to map a JSON without an element of the class

I'm having problems mapping an object using Jackson.

The issue happens when I map a JSON object that sometimes is missing an item from the class.

I'm trying to find out how to set up the configurations in order to not crash when the JSON does not have all the fields of the class.

I've already tried with:

MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

@JsonIgnoreProperties(ignoreUnknown = true)

This is the error:

com.fasterxml.jackson.databind.JsonMappingException: Instantiation of [simple type, class com.non.real.package.Like] value failed: null (through reference chain: com.non.real.package.CardFeed["likes"]->com.non.real.package.CardLikes["likes"]->java.util.ArrayList[0])


"likes": {
         "count": 0,
         "likes": []
       }

Trying different solutions I've found out that the Like object is extending the class Model of ActiveAndroid. Removing that "extension" and it works fine. I think the Model class does not work fine when it has a NULL or EMPTY.

Upvotes: 0

Views: 955

Answers (1)

nbokmans
nbokmans

Reputation: 5747

For Jackson you could try changing the mapper's configuration directly:

mapper.setSerializationInclusion(Include.NON_NULL);

But may I suggest you look at another library to map JSON to POJO? Both GSON and Genson (my personal favorite) do the same, but much faster, and much easier. Take a look at the benchmarks here, where they compare the (de)serialization of Jackson, GSON and Genson.

With Genson, it's very easy to skip null values:

private static final Genson gensonSkipNulls = new Genson.Builder().setSkipNull(true).create();

 /**
 * Deserializes JSON into a Java object.
 *
 * @param json       The JSON to deserialize.
 * @param superclass The model to deserialize the JSON into.
 * @return An object that is an instanceof superclass.
 */
public Object deserialize(final String json, final Class superclass) {
    return genson.deserialize(json, superclass);
}

Upvotes: 2

Related Questions