先定义个类做测试
class Person{ public Person() { // TODO Auto-generated constructor stub } public Person(Date bir,String name) { Birthday = bir; nameString = name; } @JSONField(format = "yyyy-MM-dd")//①注解 public Date Birthday; public String nameString; }
方法一:通过注解(类Person中①处已注解)
Person person = new Person(new Date(), "zhangsan");String json = JSON.toJSONString(person); System.out.println(json);</pre>
方法二:
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm"; String str = JSON.toJSONString(person,SerializerFeature.WriteDateUseDateFormat);
此处要注意,在Person类中就不能对Birthday进行注解了,需要将①处注释掉,不然的话方法二代码将不生效
方法三:
String jsonString = JSON.toJSONStringWithDateFormat(person, "HH:mm:ss");
Q.E.D.