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