简体   繁体   English

Jackson 自定义序列化程序,null 值被抑制

[英]Jackson custom serializer with null values to be suppressed

I have a custom serializer to treat String with blank values as null and also to trim trailing blank spaces.我有一个自定义序列化程序将带有空白值的字符串视为 null 并修剪尾随空格。 Follwoing is the code for the same.以下是相同的代码。 - -

public class StringSerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String finalValue = null;
        if (value != null) {
            finalValue = value.trim();
            if (finalValue.isEmpty()) {
                finalValue = null;
            }
        }
        gen.writeObject(finalValue);

    }

}

In the main bean definition, the attribute definition is as follows -在主bean定义中,属性定义如下——

public class SampleBean {
    private Long id;

    @JsonSerialize(using = StringSerializer.class)
    @JsonInclude(Include.NON_NULL)
    private String attribute1;

    @JsonSerialize(using = StringSerializer.class)
    @JsonInclude(Include.NON_NULL)
    private String attribute2;

    //Getters and setters
}

In the cases where the custom serializer kicks in, the not null values aren't ignored.在自定义序列化程序启动的情况下,not null 值不会被忽略。

For example:例如:

SampleBean bean = new SampleBean();
bean.setId(1L);
bean.setAttribtute1("abc");
bean.setAttribtute2(" ");
new ObjectMapper().writeValueAsString(bean);

The output of writeValueAsString: {"id": 1, "attribute1": "abc", "attribute2": null} writeValueAsString 的 output: {"id": 1, "attribute1": "abc", "attribute2": null}

Expected output since i have @JsonInclude(Include.NON_NULL) in attribute 2, is as below.预期 output 因为我在属性 2 中有 @JsonInclude(Include.NON_NULL),如下所示。 {"id": 1, "attribute1": "abc"} {“id”:1,“attribute1”:“abc”}

Is there anyway to achieve this?有没有办法做到这一点?

Try NON_EMPTY which should take care of empty and null string.尝试 NON_EMPTY ,它应该处理空字符串和 null 字符串。

@JsonSerialize(using = 
StringSerializer.class)
@JsonInclude(Include.NON_EMPTY)

If this does not meet your requirement, look here to create a Custom filter and then use it in the valueFilter如果这不符合您的要求,请查看此处以创建自定义过滤器,然后在 valueFilter 中使用它

https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html

I had exactly the same problem as you.我和你有完全一样的问题。 It is true that JsonInclude.Include.NON_EMPTY and JsonInclude.Include.NON_NULL stops working with a custom Serializer. JsonInclude.Include.NON_EMPTY 和 JsonInclude.Include.NON_NULL 确实停止使用自定义序列化程序。

I ended up creating a custom filter and used it together with the custom serializer.我最终创建了一个自定义过滤器并将其与自定义序列化程序一起使用。

Note that the example in the link https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html is wrong.请注意,链接https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html中的示例是错误的。 In the equals() method, you should return true if you DON'T want to include the field, and return false if you want to include the field in the serialized output.在 equals() 方法中,如果不想包含该字段,则应返回 true,如果要在序列化的 output 中包含该字段,则应返回 false。 This is the opposite of the example.这与示例相反。

Some sample code:一些示例代码:

/**
 * Custom Jackson Filter used for @JsonInclude. When the keywords string is empty don't include keywords in the
 * JSON serialization.
 */
public class KeywordsIncludeFilter {

    @Override
    public boolean equals(Object obj) {
        if(obj == null) return true;
        if(obj instanceof String && "".equals((String) obj)) return true;
        return false;
    }
}

Try adding the following to your StringSerializer :尝试将以下内容添加到您的StringSerializer

@Override
public boolean isEmpty(SerializerProvider provider, String value) {
    if (value != null) {
        String finalValue = value.trim();
        if (finalValue.isEmpty()) {
            return true;
        }
    }

    return false;
}

Then add the "non empty" annotation to the field in question, eg:然后将“非空”注释添加到相关字段,例如:

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

This sets the suppressible value to be "non empty" which you can then define via the isEmpty() override.这会将可抑制值设置为“非空”,然后您可以通过isEmpty()覆盖定义该值。

You are setting your value to a space instead of a null.您将值设置为空格而不是 null。

bean.setAttribtute2(" ");

Try it with a null.用 null 试试。

bean.setAttribtute2(null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM