JSON字符串格式化输出

发布时间 2023-07-14 08:51:21作者: 信铁寒胜

1、将JSON字符串格式化输出

String str = "{\"no\":\"123123\",\"nodes\":[{\"date\":\"2023-02-03 10:50\",\"node\":\"AAAA\",\"reviewer\":\"test\",\"operation\":\"通过\",\"comments\":\"没意见\"},{\"date\":\"2023-02-03 10:50\",\"node\":\"BBBB\",\"reviewer\":\"test\",\"operation\":\"\",\"comments\":\"\"}]}";
        JSONObject jsonObject = JSONObject.parseObject(str);
        String jsonFormatString = JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        System.out.println("转义前:");
        System.out.println(str);
        System.out.println("转义后:");
        System.out.println(jsonFormatString);

 2、控制台输出结果

{"no":"123123","nodes":[{"date":"2023-02-03 10:50","node":"AAAA","reviewer":"test","operation":"通过","comments":"没意见"},{"date":"2023-02-03 10:50","node":"BBBB","reviewer":"test","operation":"","comments":""}]}
转义后:
{
	"no":"123123",
	"nodes":[
		{
			"date":"2023-02-03 10:50",
			"node":"AAAA",
			"comments":"没意见",
			"reviewer":"test",
			"operation":"通过"
		},
		{
			"date":"2023-02-03 10:50",
			"node":"BBBB",
			"comments":"",
			"reviewer":"test",
			"operation":""
		}
	]
}