How to tell Jackson to ignore a field during serialization if its value is null?

后端 未结 19 1210
情歌与酒
情歌与酒 2020-11-22 04:55

How can Jackson be configured to ignore a field value during serialization if that field\'s value is null.

For example:

public class SomeClass {
            


        
19条回答
  •  -上瘾入骨i
    2020-11-22 05:12

    If you're trying to serialize a list of object and one of them is null you'll end up including the null item in the JSON even with

    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    

    will result in:

    [{myObject},null]
    

    to get this:

    [{myObject}]
    

    one can do something like:

    mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer() {
            @Override
            public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
                    throws IOException
            {
                //IGNORES NULL VALUES!
            }
        });
    
    
    

    TIP: If you're using DropWizard you can retrieve the ObjectMapper being used by Jersey using environment.getObjectMapper()

    提交回复
    热议问题