Original link: http://blog.sina.com.cn/s/blog_5f1fe33f0100jibg.html
Example code:
Jsonbean bean = new Jsonbean ();
Bean.setname ("Newbaby");
Bean.setage (1);
Bean.setborn (New Date ());
Jo = Jsonobject.fromobject (bean);
System.out.println ("Bean->json:" +jo.tostring ());
Printed result: bean->json:{"age": 1, "born": {"date": Ten, "Day": 3, "hours": +, "minutes": +, "month": 2, "Seconds": 1, "Time" : 1268201641228, "Timezoneoffset": -480, "Year": +, "name": "Newbaby"}
At this point you will find that it util the bean object. All attribute one by one of the date type is converted. In practice, in most cases we want to convert to YYYY-MM-DD, and here's how to do it.
The first thing to write a new class Jsondatevalueprocessor is as follows:
public class Jsondatevalueprocessor implements jsonvalueprocessor{
Privatestring Datepattern = "YYYY-MM-DD";
Publicjsondatevalueprocessor () {
Super ();
}
Publicjsondatevalueprocessor (String format) {
Super ();
This.datepattern = format;
}
Publicobject Processarrayvalue (Object value, Jsonconfig jsonconfig) {
return process (value);
}
Publicobject Processobjectvalue (String key, Object value,
Jsonconfig jsonconfig) {
return process (value);
}
Privateobject process (Object value) {
try {
if (value instanceof Date) {
SimpleDateFormat SDF = new SimpleDateFormat (Datepattern,
locale.uk);
Return Sdf.format ((Date) value);
}
return value = = null? "": value.tostring ();
} catch (Exception e) {
Return "";
}
}
Publicstring Getdatepattern () {
return datepattern;
}
Public Voidsetdatepattern (String pdatepattern) {
Datepattern = Pdatepattern;
}
}
Test code:
Jsonbean bean = new Jsonbean ();
Bean.setname ("Newbaby");
Bean.setage (1);
Bean.setborn (New Date ());
Jsonconfig jsonconfig = new Jsonconfig ();
Jsonconfig.registerjsonvalueprocessor (Date.class,newjsondatevalueprocessor ());
Jsonobject Jo = Jsonobject.fromobject (bean, jsonconfig);
System.out.println ("Bean->json:" +jo.tostring ());
Print Result: bean->json:{"age": 1, "Born": "2010-03-10", "name": "Newbaby"}
This will give us the results we want.
Bean with date converted to JSON (Bean->json)