fastjson2全局配置长整型Long、日期Date、字符串String等默认序列化格式
保证程序启动后立即执行如下代码
JSON.configWriterDateFormat("yyyy-MM-dd HH:mm:ss");
JSON.configReaderDateFormat("yyyy-MM-dd HH:mm:ss");
JSON.config(JSONWriter.Feature.WriteNullNumberAsZero, // Long等Number类型值为空序列化为0JSONWriter.Feature.WriteNullBooleanAsFalse, // Boolean类型值为空序列化为falseJSONWriter.Feature.WriteLongAsString, // Long类型序列化为字符串JSONWriter.Feature.WriteNullListAsEmpty, // List类型值为空序列化为[]JSONWriter.Feature.WriteBigDecimalAsPlain, // BigDecimal类型序列化为非科学计数法JSONWriter.Feature.PrettyFormat, // 格式化输出JSONWriter.Feature.WriteNullStringAsEmpty); // String类型值为空序列化为""
JSON.config(JSONReader.Feature.AllowUnQuotedFieldNames); // 字段名称支持没有双引号的反序列化
// 当序列化的值为字符串时直接输出字符串,而不是再加一层引号或双引号,如`JSON.toJSONString("test")`直接输出"test",而不是"\"test\""
JSON.register(String.class, new ObjectWriterPrimitiveImpl<String>(){@Overridepublic void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {jsonWriter.writeRaw((String) object);}
});
假设你是springboot项目,那么可以使用@Configuration
、@PostConstruct
等注解
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.writer.ObjectWriterPrimitiveImpl;
import org.springframework.context.annotation.Configuration;import java.lang.reflect.Type;@Configuration
public class FastJsonConfig {static {JSON.configWriterDateFormat("yyyy-MM-dd HH:mm:ss");JSON.configReaderDateFormat("yyyy-MM-dd HH:mm:ss");JSON.config(JSONWriter.Feature.WriteNullNumberAsZero, // Long等Number类型值为空序列化为0JSONWriter.Feature.WriteNullBooleanAsFalse, // Boolean类型值为空序列化为falseJSONWriter.Feature.WriteLongAsString, // Long类型序列化为字符串JSONWriter.Feature.WriteNullListAsEmpty, // List类型值为空序列化为[]JSONWriter.Feature.WriteBigDecimalAsPlain, // BigDecimal类型序列化为非科学计数法JSONWriter.Feature.PrettyFormat, // 格式化输出JSONWriter.Feature.WriteNullStringAsEmpty); // String类型值为空序列化为""JSON.config(JSONReader.Feature.AllowUnQuotedFieldNames); // 字段名称支持没有双引号的反序列化// 当序列化的值为字符串时直接输出字符串,而不是再加一层引号或双引号,如`JSON.toJSONString("test")`直接输出"test",而不是"\"test\""JSON.register(String.class, new ObjectWriterPrimitiveImpl<String>(){@Overridepublic void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {jsonWriter.writeRaw((String) object);}});}
}