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

后端 未结 19 1201
情歌与酒
情歌与酒 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条回答
  • 2020-11-22 05:04

    You can use the following mapper configuration:

    mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
    

    Since 2.5 you can user:

    mapper.setSerializationInclusion(Include.NON_NULL);
    
    0 讨论(0)
  • 2020-11-22 05:05

    Jackson 2.x+ use

    mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);
    
    0 讨论(0)
  • 2020-11-22 05:09

    This Will work in Spring boot 2.0.3+ and Jackson 2.0+

    import com.fasterxml.jackson.annotation.JsonInclude;
    
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class ApiDTO
    {
        // your class variable and 
        // methods
    }
    
    0 讨论(0)
  • 2020-11-22 05:11

    Case one

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String someString;
    

    Case two

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private String someString;
    

    If someString is null, it will be ignored on both of cases. If someString is "" it just only be ignored on case two.

    The same for List = null or List.size() = 0

    0 讨论(0)
  • 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<Object>() {
            @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()

    0 讨论(0)
  • 2020-11-22 05:15
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    

    should work.

    Include.NON_EMPTY indicates that property is serialized if its value is not null and not empty. Include.NON_NULL indicates that property is serialized if its value is not null.

    0 讨论(0)
提交回复
热议问题