- 通过普通的转化与带有时间的转化对比
public static void main(String[] args) {
List<Map<String ,Object>> list = new ArrayList();
Map<String ,Object> map = new HashMap<>();
Person p = new Person("张三", "女", new Date());
map.put("1", p);
Person p1 = new Person("李四", "男", new Date());
map.put("2", p1);
list.add(map);
String s = JSONObject.toJSONString(list);
String s1 = JSONObject.toJSONStringWithDateFormat(list, JSON.DEFFAULT_DATE_FORMAT);
System.out.println("s执行结果: "+s);
System.out.println("s1执行结果: "+s1);
}
创建的Person类
public class Person implements Serializable {
private String name;
private String sex;
private Date date;
public Person(String name, String sex, Date date) {
this.name = name;
this.sex = sex;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
- 执行结果
s执行结果: [{"1":{"date":1672990998981,"name":"张三","sex":"女"},"2":{"date":1672990998981,"name":"李四","sex":"男"}}]
s1执行结果: [{"1":{"date":"2023-01-06 15:43:18","name":"张三","sex":"女"},"2":{"date":"2023-01-06 15:43:18","name":"李四","sex":"男"}}]
-
结论
对比结果很容易看出,该方法可以将时间转化成可读的String串。 -
使用前提
在maven中导入此依赖<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version> </dependency>