Next, let's take a look at the following code:
Person. Java:
public class Person {private Date hire;public Date getHire() {return hire;}public void setHire(Date hire) {this.hire = hire;}public Person() {super();}public Person(Date hire) {super();this.hire = hire;}}
Test. Java:
public class Test {public static void main(String[] args) {test();}public static void test(){Person p=new Person(new Date());JSONObject json=JSONObject.fromObject(p);String json_str=json.toString();System.out.println(json_str);}}
Run the program to obtain:
{"hire":{"date":20,"day":4,"hours":17,"minutes":21,"month":5,"seconds":16,"time":1371720076781,"timezoneOffset":-480,"year":113}}
This is obviously not the expected format. How can this problem be solved? In fact, the imported jar package has reserved the required interfaces for us.Jsonvalueprocessor.
We can write a converter and select the interface jsonvalueprocessor reserved for us by the implementation framework to implement the methods in the interface and implement the required conversion logic in these methods.
Dateprocessor. Java:
public class DateProcessor implements JsonValueProcessor {private String pattern="yyyy-MM-dd";public void setPattern(String pattern) {this.pattern = pattern;}@Overridepublic Object processArrayValue(Object arg0, JsonConfig arg1) {Date date=(Date)arg0;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}@Overridepublic Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {Date date=(Date)arg1;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}}
Then rewriteTest. Java:
public class Test {public static void main(String[] args) {test();}public static void test(){Person p=new Person(new Date());DateProcessor processor=new DateProcessor();JsonConfig config=new JsonConfig();config.registerJsonValueProcessor(Date.class,processor);JSONObject json=JSONObject.fromObject(p,config);String json_str=json.toString();System.out.println(json_str);}}
Then run the program to obtain:
{"hire":"2013-06-20"}
In this way, the date type can be converted to the desired format.