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