writeValueAsString 方法
@Data
@AllArgsConstructor
public class ResultVO {
@ApiModelProperty("是否創(chuàng)建成功凿宾,true成功")
@JsonProperty("retStatus")
private String status;
@ApiModelProperty("流程id,OA系統(tǒng)唯一標(biāo)識(shí)")
@JsonProperty("retCode")
private String code;
@ApiModelProperty("返回消息")
@JsonProperty("retMessage")
private String message;
@ApiModelProperty("跳轉(zhuǎn)路徑")
private String url;
public static void main(String[] args) throws JsonProcessingException {
ResultVO resultVO = new ResultVO("true", "123", "創(chuàng)建成功", "/workFlow/aa.jsp");
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultVO);
System.out.println(jsonStr);
}
}
objectMapper.writerWithDefaultPrettyPrinter() 這個(gè)方法將輸出格式化了剃幌,顯示更漂亮旬陡,可用可不用
結(jié)果輸出.png
**20220906 增加對(duì)結(jié)果中的null 進(jìn)行處理浑塞,null轉(zhuǎn)換成空串 "" **
ObjectMapper objectMapper = new ObjectMapper();
// 處理序列化,將 null 轉(zhuǎn)換為 "" 孕惜,要求不能出現(xiàn) {}
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
});
String str = objectMapper.writeValueAsString(contractRenewVO);
// 轉(zhuǎn)換成json愧薛,會(huì)默認(rèn)忽略掉null值,如果轉(zhuǎn)換成JSONObject衫画,可能會(huì)出現(xiàn)null 變成 {}的問(wèn)題
JSON json = JSONUtil.parse(str);
log.info("數(shù)據(jù)對(duì)象: {}", json);