Jackson Parser: ignore deserialization for type mismatch

I get the following response generated by cakephp server

  [ { "id": "42389", "start": "0000-00-00", "end": "0000-00-00", "event_id": null, "trip_id": "5791", "location_id": "231552", "user_id": "105", "users_attending": "0", "user_local": "0", "Trip": { "name": "Asdas" }, "Event": [], "Location": { "name": "South Melbourne" } }, { "id": "42392", "start": "0000-00-00", "end": "0000-00-00", "event_id": "1218", "trip_id": "4772", "location_id": "271505", "user_id": "105", "users_attending": "3", "user_local": "50", "Trip": { "name": "trip by 1059200" }, "Event": { "title": "SampleEvent 454", "id": "1218" }, "Location": { "name": "Houston" } }, ....... ] 

The fact is that the parser expects an Event object, but if it is null , then it receives an empty array.

Since the response is auto- cakephp using cakephp , it needs to be modified in many places on the server side.

Is there a simple way for a jackson to ignore the Event property if its array is empty?

EDIT:

I tried to have two properties called Event : one array and another object, but that didn't work either.

+3
source share
3 answers

Since I had to process such an answer for many objects, I finally proceeded to create a generic class that would return a Deserializer for a particular class .

Here is what I used

 public class Deserializer<T> { public JsonDeserializer<T> getDeserializer(final Class<T> cls) { return new JsonDeserializer<T> (){ @Override public T deserialize(JsonParser jp, DeserializationContext arg1) throws IOException, JsonProcessingException { JsonNode node = jp.readValueAsTree(); if (node.isObject()) { return new ObjectMapper().convertValue(node, cls); } return null; } }; } 

}

+1
source

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

Another option is to use a common supertype, which will mean java.lang.Object , and you will get either List (for a JSON array) or Map (for a JSON object). But you will need to do post processing to bind to specific types.

+1
source

What I found the simplest solution to this problem is to add a function:

 DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true 

to my object mapper. Jackson will do the rest for you. See https://fasterxml.imtqy.com/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.html .

This answer gives a detailed explanation: stack overflow

0
source

All Articles