How to Use gson to handle JSON-converted timestamp type

Source: Internet
Author: User

Problem:The project uses gson for JSON conversion. However, when processing the date type in the object, the date format is "11:11:11", which is not our expectation "11:11:11 ".

Solution Process:

Search for the solution on the Internet as follows:

Original code: Private Static final gson = new gson ();

New Code: Private Static final gson = new gsonbuilder (). setdateformat ("yyyy-mm-dd hh: mm: SS"). Create ();

After the change, I tested it and it didn't work. It's strange! After dubug, we found that the date type in the object is timestamp because hibernate was used. The above settings do not work. Next, I found another solution, as shown below:

First create a type Adapter

   public class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp>{     private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");         public JsonElement serialize(Timestamp ts, Type t, JsonSerializationContext jsc) {             String dfString = format.format(new Date(ts.getTime()));             return new JsonPrimitive(dfString);         }         public Timestamp deserialize(JsonElement json, Type t, JsonDeserializationContext jsc) throws JsonParseException {             if (!(json instanceof JsonPrimitive)) {                 throw new JsonParseException("The date should be a string value");             }                 try {                 Date date = format.parse(json.getAsString());                 return new Timestamp(date.getTime());             } catch (ParseException e) {                 throw new JsonParseException(e);             }         }     } 

Application 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()));

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.