JSON-to-bean transfer, timestamp type problems

Source: Internet
Author: User
Tags dateformat

When JSON and Java beans are converted to each other, the timestamp field in the bean cannot be processed directly, and two converters need to be implemented.

The Datejsonvalueprocessor function is to convert the Timepstamp to the specified time format when the Bean is converted to JSON.

1 ImportJava.text.DateFormat;2 ImportJava.text.SimpleDateFormat;3 Importjava.util.Date;4 ImportNet.sf.json.JsonConfig;5 ImportNet.sf.json.processors.JsonValueProcessor;6 /*** Convert a timestamp in a bean to a date string in JSON*/7  Public classDatejsonvalueprocessorImplementsJsonvalueprocessor {8      Public Static FinalString Default_date_pattern = "Yyyy-mm-dd";9     PrivateDateFormat DateFormat;Ten      Publicdatejsonvalueprocessor (String datepattern) { One         Try{ ADateFormat =NewSimpleDateFormat (Datepattern);} -         Catch(Exception e) { -DateFormat =NewSimpleDateFormat (default_date_pattern); the         } -     } -      PublicObject Processarrayvalue (object value, Jsonconfig jsonconfig) { -         returnprocess (value); +     } -      PublicObject Processobjectvalue (String key, Object Value,jsonconfig jsonconfig) { +         returnprocess (value); A     } at     PrivateObject Process (object value) { -         returnDateformat.format ((Date) value); -     } -}

Timestampmorpher, in contrast to Datejsonvalueprocessor, converts the specified time format to timestamp when JSONL is converted to a bean.

1 ImportJava.sql.Timestamp;2 Importjava.text.ParseException;3 ImportJava.text.SimpleDateFormat;4 Importnet.sf.ezmorph.MorphException;5 ImportNet.sf.ezmorph.object.AbstractObjectMorpher;6 /*** Converts a date string in a JSON string into a timestamp in a bean*/7  Public classTimestampmorpherextendsAbstractobjectmorpher {8 /*** Date string format*/9 Privatestring[] formats;Ten  PublicTimestampmorpher (string[] formats) { One      This. formats =formats; A } -  Publicobject Morph (object value) { - if(Value = =NULL){ the     return NULL; - } - if(Timestamp.class. IsAssignableFrom (Value.getclass ())) { -     return(Timestamp) value; + } - if( !supports (Value.getclass ())) { +     Throw NewMorphexception (Value.getclass () + "is unsupported type"); A } atString strvalue=(String) value; -SimpleDateFormat dateparser=NULL; -  for(inti = 0; i < formats.length; i++ ){ -     if(NULL==Dateparser) { -Dateparser=NewSimpleDateFormat (Formats[i]); -}Else{ in Dateparser.applypattern (Formats[i]); -     } to     Try{ +         return NewTimestamp (Dateparser.parse (Strvalue.tolowercase ()). GetTime ()); -     Catch(ParseException e) { the         //e.printstacktrace (); *     } $ }Panax Notoginseng return NULL; - } the @Override +  PublicClass Morphsto () { A     returnTimestamp.class; the } +  Public Booleansupports (Class clazz) { -     returnString.class. IsAssignableFrom (clazz); $ } $  -}

Test it for a moment.

1  Public classJsontest {2  Public Static voidMain (string[] args) {3String jsonstr= "{\" id\ ": \" 101\ ", \" name\ ": \" Zhang san \ ", \" age\ ": \" 20\ ", \" birthday\ ": \" 1992-10-19 23:52:18\ "}";4Student s=NewStudent ();5Timestamp b=timestamp.valueof ("1992-10-19 23:52:18");6S.setid (123456);7S.setname ("John Doe");8S.setage (20);9 S.setbirthday (b);TenStudent s1=Jsontobean (JSONSTR); One System.out.println (S1.getbirthday ()); A System.out.println (Beantojson (s)); - } -  Public StaticStudent Jsontobean (String json) { theString[] formats={"Yyyy-mm-dd HH:mm:ss", "YYYY-MM-DD"}; -Jsonutils.getmorpherregistry (). Registermorpher (NewTimestampmorpher (formats)); -Jsonobject jsonobject=Jsonobject.fromobject (JSON); -     return(Student) Jsonobject.tobean (jsonobject,student.class); + } -  +  Public StaticString Beantojson (Student s) { AJsonconfig config=Newjsonconfig (); atConfig.registerjsonvalueprocessor (Timestamp.class,NewDatejsonvalueprocessor ("Yyyy-mm-dd HH:mm:ss")); -Jsonobject json=Jsonobject.fromobject (s,config); -     returnjson.tostring ();} -}

JSON-to-bean transfer, timestamp type problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.