Google GSON GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")不能格式化Data
2012-11-23 16:01
579 查看
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,再试,成功。另搜索到网上一哥们的其他解法,如下:
首先创建一个类型适配器
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);
}
}
}
应用类型适配器
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()));
相关文章推荐
- Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
- struts标签格式化时间<s:date name="neowaveBloodPressure.monitorTime" format="yyyy-MM-dd HH:mm:ss" />
- 写一个方法对日期格式化 new Date().format("yyyy-MM-dd HH:mm:ss")
- 通过 DataFormatString="{0:yyyy/MM/dd}" HtmlEncode="false" 格式化显示时间
- .net 日期格式化("yyyy-MM-dd HH:mm:ss.ffffff zzz”)(转)
- Java continue break 制作简单聊天室程序,屏蔽不文明语言,显示每句话聊天时间 for(;;) SimpleDateFormat("yyyy-MM-dd hh:mm:ss") equalsIgnoreCase
- 时间转换的好用方法(好招1)//Date date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2007-09-21 11:00:10.0100");
- 用 SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 做文件名要注意的。:
- String.Format("{0:yyyy-MM-dd}" ,dr["ar_time"].toString())不能格式化的问题
- 在gridview里对日期字段设置dataformatstring="{0:yyyy-MM-dd}"没有任何作用的解决方法
- js扩展Date将时间格式化为"yyyy-MM-dd hh:mm:ss"格式的字符串
- 向mysql中插入格式为"yyyy-MM-dd HH:mm:ss"的时间
- JS获取当前时间并格式化"yyyy-MM-dd HH:mm:ss"
- Asp.Net2.0中GridView的DataFormatString="{0:yyyy-MM-dd}"不起作用解决办法
- String.Format("{0:yyyy-MM-dd}" ,dr["ar_time"].toString())不能格式化的问题
- new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")?
- 将Json中的datetime的UTC表示形式转换为:"yyyy-MM-dd"或"yyyy-MM-dd HH:mm:ss"字符串表示形式
- 格式化时间戳"yyyy-MM-dd HH:mm:ss"
- 获取当前的日期时间 格式“yyyy-MM-dd HH:MM:SS"
- JSON 序列化和反序列化:将时间由"//Date(10000000000-0700)//" 格式转换成 "yyyy-MM-dd HH:mm:ss" 格式的字符串