[英]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.