`
m635674608
  • 浏览: 4930445 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

用gson如何处理json转换Timestamp类型

    博客分类:
  • java
 
阅读更多

问题: 项目中使用gson进行json的转换,但是在处理对象中的日期类型时,日期格式为“2011-8-31 11:11:11”不是我们期望的“2011-08-31 11:11:11”。

解决过程:

       到网上搜索了一下解决方案如下

        原代码: private static final Gson GSON = new Gson();

         新代码:private static final Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

      改后测试了一下,竟然不起作用,奇怪!接着dubug了一下,发现原来因为使用了hibernate,对象中的日期类型时timestamp类型。上面的设置没起作用。接着又找了一下,还有对应方案如下

 首先创建一个类型适配器

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

 应用类型适配器

 

[java] view plaincopy
  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()));  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics