writeValueAsString 方法
@Data
@AllArgsConstructor
public class ResultVO {
@ApiModelProperty("是否创建成功,true成功")
@JsonProperty("retStatus")
private String status;
@ApiModelProperty("流程id,OA系统唯一标识")
@JsonProperty("retCode")
private String code;
@ApiModelProperty("返回消息")
@JsonProperty("retMessage")
private String message;
@ApiModelProperty("跳转路径")
private String url;
public static void main(String[] args) throws JsonProcessingException {
ResultVO resultVO = new ResultVO("true", "123", "创建成功", "/workFlow/aa.jsp");
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultVO);
System.out.println(jsonStr);
}
}
objectMapper.writerWithDefaultPrettyPrinter() 这个方法将输出格式化了,显示更漂亮,可用可不用
**20220906 增加对结果中的null 进行处理,null转换成空串 "" **
ObjectMapper objectMapper = new ObjectMapper();
// 处理序列化,将 null 转换为 "" ,要求不能出现 {}
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);
// 转换成json,会默认忽略掉null值,如果转换成JSONObject,可能会出现null 变成 {}的问题
JSON json = JSONUtil.parse(str);
log.info("数据对象: {}", json);