Gson conversion Timestamp type "2012-11-3 10:49:15"--> "2012-11-03 10:49:15"

Source: Internet
Author: User

issue: using Gson for JSON conversion in the project, but when working with date types in an object, the date format of "2011-8-31 11:11:11" is not what we would expect from "2011-08-31 11:11:11".

resolution process:

Search the Internet for the following solution

Original code: private static final Gson Gson = new Gson ();

New code: private static final Gson Gson = new Gsonbuilder (). Setdateformat ("Yyyy-mm-dd HH:mm:ss"). Create ();

After the test, it did not work, strange. Then Dubug, found that because of the use of Hibernate, the date type in the object timestamp type. The settings above do not work. Then I looked for it, and there was a corresponding scheme as follows


first create a type adapter PublicclassTimestamptypeadapterImplementsJsonserializer<timestamp> a jsondeserializer<timestamp>{.PrivateFinalDateFormat format =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); PublicJsonelement Serialize (Timestamp ts, Type T, Jsonserializationcontext JSC) {String dfstring = Format.format (NewDate (Ts.gettime ())); returnNewJsonprimitive (dfstring); } PublicTimestamp Deserialize (jsonelement json, Type T, Jsondeserializationcontext JSC)throwsjsonparseexception {if(! (JSONinstanceofjsonprimitive)) {ThrowNewJsonparseexception ("The date should be a string value"); }Try{Date date = Format.parse (Json.getasstring ()); returnNewTimestamp (Date.gettime ()); }Catch(ParseException e) {ThrowNewJsonparseexception (e); }            }        }

Apply type adapter gsonbuilder gsonbuilder =  new  gsonbuilder ();   Gsonbuilder.setdateformat ("Yyyy-mm-dd hh:mm:ss");   gsonbuilder.registertypeadapter (Timestamp. Class , new  timestamptypeadapter ());   gson gson =  Gsonbuilder.create ();   String json = gson.tojson ( new  timestamp ( ( new  date ()). GetTime ()); &NBSP

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.