Google GSON GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")不能格式化Data

来源:互联网 发布:北京知名软件外国企业 编辑:程序博客网 时间:2024/06/13 18:36

Google GSON GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")不能格式化Data

在项目中遇到问题,数据库中保存的时间类型为datetime(MySQL),实体类中对应数据类型为java.sql.Date,利用GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")构造gson对象向客户端输出json字符串。忽一日客户端接收到的日期字段值为中文时间,大惊,彻查,疑为实体类中的数据类型不适合,导致Hibernate中的timestamp部分信息丢失,尝试着将实体类中类型改为java.sql.Timestamp,再试,成功。

另搜索到网上一哥们的其他解法,如下:

 首先创建一个类型适配器

  1. public class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp>{  
  2.      private final DateFormat format new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      
  3.      public JsonElement serialize(Timestamp ts, Type t, JsonSerializationContext jsc)      
  4.          String dfString format.format(new Date(ts.getTime()));      
  5.          return new JsonPrimitive(dfString);      
  6.           
  7.      public Timestamp deserialize(JsonElement json, Type t, JsonDeserializationContext jsc) throws JsonParseException      
  8.          if (!(json instanceof JsonPrimitive))      
  9.              throw new JsonParseException("The date should be string value");      
  10.               
  11.       
  12.          try      
  13.              Date date format.parse(json.getAsString());      
  14.              return new Timestamp(date.getTime());      
  15.          catch (ParseException e)      
  16.              throw new JsonParseException(e);      
  17.               
  18.           
  19.   

 

应用类型适配器

  1. GsonBuilder gsonBuilder new GsonBuilder();  
  2. gsonBuilder.setDateFormat("yyyy-MM-dd hh:mm:ss");  
  3. gsonBuilder.registerTypeAdapter(Timestamp.class,new TimestampTypeAdapter());  
  4. Gson GSON gsonBuilder.create();  
  5. String json GSON.toJson(new Timestamp((new Date()).getTime()));