Jackson deserialize nulls to empty list with no access to entity

What I am trying to achieve:

to deserialize null values to empty lists

Note: I cannot change/annotate the entities, because they do come from a jar.

I have the following code:

import com.fasterxml.jackson.annotation.JsonInclude;

import com.fasterxml.jackson.annotation.JsonSetter;

import com.fasterxml.jackson.annotation.Nulls;

import com.fasterxml.jackson.core.JsonParser;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.core.type.TypeReference;

import com.fasterxml.jackson.databind.*;

import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;

import java.util.Collections;

import java.util.List;

public class MyJsonMapperList extends ObjectMapper{

private static final MyJsonMapperList jsonMapper = new MyJsonMapperList();

public MyJsonMapperList() {

SimpleModule sm = new SimpleModule();

sm.addDeserializer(List.class, new NullToEmptyListDeserializer());

super.registerModule(sm);

// setSerializationInclusion(JsonInclude.Include.NON_NULL);

// disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

}

private static class NullToEmptyListDeserializer extends JsonDeserializer {

@Override

public List deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {

ObjectMapper mapper = new ObjectMapper();

mapper.configOverride(List.class).setSetterInfo(JsonSetter.Value.forContentNulls(Nulls.AS_EMPTY));

mapper.configOverride(List.class).setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));

mapper.configOverride(List.class).setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY, Nulls.AS_EMPTY));

return mapper.readValue(jsonParser, new TypeReference(){});

}

@Override

public List getNullValue(DeserializationContext ctx) {

return Collections.emptyList();

}

}

public static ...

Read More »

By: StackOverFlow - 7 days ago

Related Posts