前言
在使用 fastjson 存储 json 对象时,发现其将 date 类型的 value 默认转换成了 long 类型的时间戳。
那么怎么解决这个问题?
代码如下
private static SerializeConfig mapping = new SerializeConfig();
private static String dateFormat;
static {
dateFormat = "yyyy-MM-dd HH:mm:ss";
}
@org.junit.Test
public void testJSon() {
JSONObject json1 = new JSONObject();
json1.put("date", new Date());
System.out.println(json1.toJSONString());
System.out.println(JSONObject.toJSONString(json1));
System.out.println(toJSON(json1));
}
public static String toJSON(Object jsonText) {
return JSON.toJSONString(jsonText, SerializerFeature.WriteDateUseDateFormat);
}
/**
* 自定义时间格式
*
* @param jsonText
* @return
*/
public static String toJSON(String dateFormat, String jsonText) {
mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
return JSON.toJSONString(jsonText, mapping);
}
通过更改 json 的序列化 config,输出结果如下:
{"date":1564497393215}
{"date":1564497393215}
{"date":"2019-07-30 22:36:33"}