package com.test.base; import java.lang.reflect.Type; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> { private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public Timestamp deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { if (!(jsonElement instanceof JsonPrimitive)) { throw new JsonParseException("The data should be a string value"); } try { Date date = format.parse(jsonElement.getAsString()); return new Timestamp(date.getTime()); } catch (ParseException e) { throw new JsonParseException(e); } } @Override public JsonElement serialize(Timestamp timestamp, Type type, JsonSerializationContext jsonSerializationContext) { String dataFormatAsString = format.format(new Date(timestamp.getTime())); return new JsonPrimitive(dataFormatAsString); } }
@Test public void gsonTest() { Gson gson1 = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create(); CascadeReport tem = new CascadeReport(); tem.setDate(new Timestamp(new Date().getTime())); tem.setDepartment("武汉刑侦"); String jsonString = gson1.toJson(tem, CascadeReport.class); System.out.println(jsonString); ////////////////////////////////////////////////////////// String reportData = "[{date:\"2016-01-01 09:00:01\",department:\"xxxx\",ipAddress:\"192.168.120.120\",failedNum:2,ruleIDs:\"1002,1003\",regionCode:168430083,account:\"李四\",type:1 }]"; List<CascadeReport> list = gson.fromJson(reportData, new TypeToken<List<CascadeReport>>() { }.getType()); System.out.println(list.get(0).getDate().toGMTString()); }