Skip to content Skip to sidebar Skip to footer

Jackson Parser: Ignore Deserializing For Type Mismatch

I am getting following response generated from the server by cakephp [ { 'id': '42389', 'start': '0000-00-00', 'end': '0000-00-00', 'event_id': null, 'trip_id': '5791',

Solution 1:

Since, I had to handle response like this for many objects I finally went ahead with creating a generic class which would return a Deserializer for a specific class.

Here is what I used

publicclassDeserializer<T> {

  public JsonDeserializer<T> getDeserializer(final Class<T> cls) {
      returnnewJsonDeserializer<T> (){

         @Overridepublic T deserialize(JsonParser jp, DeserializationContext arg1)throws IOException, JsonProcessingException {
            JsonNodenode= jp.readValueAsTree();
            if (node.isObject()) {
              returnnewObjectMapper().convertValue(node, cls);
            }
            returnnull;
         }
     };
}

}

Solution 2:

I think it makes sense to separate it, if types are incompatible.

The other option would have been to use a common super-type, which would mean java.lang.Object, and you would get either List (for JSON array) or Map (for JSON Object). But would need to do post-processing to bind into concrete types.

Solution 3:

What I found the easiest solution to this problem was adding the feature:

DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true

to my objectmapper. Jackson does the rest for you. See https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.html.

This answer gives an in depth explanation: https://stackoverflow.com/a/22956168/9279756

Post a Comment for "Jackson Parser: Ignore Deserializing For Type Mismatch"