[英]How to treat JSON Value as String Object in Java using ObjectMapper?
[英]ObjectMapper - How to send null value in JSON
根據第三方API規范,如果不存在值,我需要使用ObjectMapper
在JSON中發送空值,
預期結果: "optional": null
如果存在可選值,則發送"optional": "value"
碼:
requestVO = new RequestVO(optional);
ObjectMapper mapper = new ObjectMapper();
String requestString = mapper.writeValueAsString(requestVO);
類:
public class RequestVO {
String optional;
public RequestVO(String optional) {
this.optional = optional;
}
public String getOptional() {
return optional;
}
public void setOptional(String optional) {
this.optional= optional;
}
將@JsonInclude(JsonInclude.Include.USE_DEFAULTS)
注釋添加到您的類中。
@JsonInclude(JsonInclude.Include.USE_DEFAULTS)
class RequestVO {
String optional;
public RequestVO(String optional) {
this.optional = optional;
}
public String getOptional() {
return optional;
}
public void setOptional(String optional) {
this.optional = optional;
}
}
示例:
RequestVO requestVO = new RequestVO(null);
ObjectMapper mapper = new ObjectMapper();
try {
String requestString = mapper.writeValueAsString(requestVO);
System.out.println(requestString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
輸出:
{"optional":null}
有價值:
RequestVO requestVO = new RequestVO("test");
ObjectMapper mapper = new ObjectMapper();
try {
String requestString = mapper.writeValueAsString(requestVO);
System.out.println(requestString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
輸出:
{"optional":"test"}
您可以在偶數屬性上使用@JsonInclude
批注。 因此,這樣您可以序列化為null或在序列化時忽略某些屬性。
您可以這樣配置ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
如果JSON請求中沒有值,則您處理的將按預期為null
。
如果需要,您甚至可以為ObjectMapper
配置Spring
bean。
編輯:
我誤解了這個問題,他對JSON響應感興趣,而不是解析對象。 這種情況的正確屬性是JsonInclude.Include.USE_DEFAULTS
。
為混亂道歉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.