[英]Jackson custom serializer with null values to be suppressed
我有一个自定义序列化程序将带有空白值的字符串视为 null 并修剪尾随空格。 以下是相同的代码。 -
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);
}
}
在主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
}
在自定义序列化程序启动的情况下,not null 值不会被忽略。
例如:
SampleBean bean = new SampleBean();
bean.setId(1L);
bean.setAttribtute1("abc");
bean.setAttribtute2(" ");
new ObjectMapper().writeValueAsString(bean);
writeValueAsString 的 output: {"id": 1, "attribute1": "abc", "attribute2": null}
预期 output 因为我在属性 2 中有 @JsonInclude(Include.NON_NULL),如下所示。 {“id”:1,“attribute1”:“abc”}
有没有办法做到这一点?
尝试 NON_EMPTY ,它应该处理空字符串和 null 字符串。
@JsonSerialize(using =
StringSerializer.class)
@JsonInclude(Include.NON_EMPTY)
如果这不符合您的要求,请查看此处以创建自定义过滤器,然后在 valueFilter 中使用它
https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html
我和你有完全一样的问题。 JsonInclude.Include.NON_EMPTY 和 JsonInclude.Include.NON_NULL 确实停止使用自定义序列化程序。
我最终创建了一个自定义过滤器并将其与自定义序列化程序一起使用。
请注意,链接https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html中的示例是错误的。 在 equals() 方法中,如果不想包含该字段,则应返回 true,如果要在序列化的 output 中包含该字段,则应返回 false。 这与示例相反。
一些示例代码:
/**
* 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;
}
}
尝试将以下内容添加到您的StringSerializer
:
@Override
public boolean isEmpty(SerializerProvider provider, String value) {
if (value != null) {
String finalValue = value.trim();
if (finalValue.isEmpty()) {
return true;
}
}
return false;
}
然后将“非空”注释添加到相关字段,例如:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String attribute2;
这会将可抑制值设置为“非空”,然后您可以通过isEmpty()
覆盖定义该值。
您将值设置为空格而不是 null。
bean.setAttribtute2(" ");
用 null 试试。
bean.setAttribtute2(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.