Raipe
Raipe

Reputation: 807

Jackson null list to empty array serialization

I want to serialize null List to empty array.

So given:

class MyBean { List values; }

And given an instance with null for values, it should be serialized to:

{ "values": [] }

I want this to be global behaviour for all Lists in all classes. I do not want to add any annotations or specific handling for classes.

I have read all related questions I found, and could not come up with anything that works. Seems any custom serializer I try to register for List class is not kicking in.

If you have this working on your project, let me know how did you manage to do that.

Upvotes: 3

Views: 5416

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38720

In cases like this you need to customize JacksonAnnotationIntrospector class. Te serialize null-s, by default, Jackson uses com.fasterxml.jackson.databind.ser.std.NullSerializer class. You can extend default introspector class and override findNullSerializer.

See below example:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setAnnotationIntrospector(new EmptyArrayJacksonAnnotationIntrospector());
        mapper.writeValue(System.out, new ListWrapper());
    }
}

class EmptyArrayJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector {

    @Override
    public Object findNullSerializer(Annotated a) {
        if (List.class.isAssignableFrom(a.getRawType())) {
            return ArrayNullSerializer.INSTANCE;
        }
        return super.findNullSerializer(a);
    }
}

final class ArrayNullSerializer extends StdSerializer<Object> {

    public static final ArrayNullSerializer INSTANCE = new ArrayNullSerializer();

    protected ArrayNullSerializer() {
        super(Object.class);
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartArray();
        gen.writeEndArray();
    }
}

class ListWrapper {

    private List values;

    public List getValues() {
        return values;
    }

    public void setValues(List values) {
        this.values = values;
    }
}

Above code prints:

{"values":[]}

Upvotes: 4

Related Questions