Json 格式化工具类
1、使用Jackson的DefaultPrettyPrinter来格式化json
public static String formatJson(Object obj) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter(" ", DefaultIndenter.SYS_LF);
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentObjectsWith(indenter);
printer.indentArraysWith(indenter);
return mapper.writer(printer).writeValueAsString(obj);
}
2、使用Jackson的ObjectMapper的writerWithDefaultPrettyPrinter()来格式化json
public static String formatJson2(Object obj) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
3、使用FastJson来格式化json
public static String formatJson3(Object obj) {
String pretty = JSON.toJSONString(obj, SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.DisableCircularReferenceDetect);
return pretty;
}
4、使用Gson来格式化json
public static String formatJson4(Object obj) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(obj);
}
5、完整代码
package cn.lyf.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public final class JsonUtil {
private JsonUtil() {
}
public static String formatJson(Object obj) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter(" ", DefaultIndenter.SYS_LF);
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentObjectsWith(indenter);
printer.indentArraysWith(indenter);
return mapper.writer(printer).writeValueAsString(obj);
}
public static String formatJson2(Object obj) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
public static String formatJson3(Object obj) {
String pretty = JSON.toJSONString(obj, SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.DisableCircularReferenceDetect);
return pretty;
}
public static String formatJson4(Object obj) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(obj);
}
}