package me.jar.practise.json; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; public final class JsonUtils { private static final SerializeConfig config; static { // 设置日期转字符串的格式 JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // 设置输出transient修饰的属性 JSON.DEFAULT_GENERATE_FEATURE = SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, SerializerFeature.SkipTransientField, false); config = new SerializeConfig(); // 设置禁止ASM序列化,配合WriteMapNullValue,null值的属性也打印出来 config.setAsmEnable(false); } private JsonUtils() { // 工具类,添加私有构造器,防止实例化 } /** * 将对象转成JSON格式的字符串返回 * * @param obj 对象 * @return 字符串 */ public static String ObjectToJsonString(Object obj) { if (obj == null) { return "{}"; } return JSON.toJSONString(obj, config, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect); } }