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,再试,成功。
另搜索到网上一哥们的其他解法,如下:
- public
class TimestampTypeAdapter implementsJsonSerializer<Timestamp>, JsonDeserializer<Timestamp>{ -
private final DateFormat newformat = SimpleDateFormat( "yyyy-MM-ddHH: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 throwsdeserialize(JsonElement json, Type t, JsonDeserializationConte xt jsc) JsonParseException { -
if (!(json instanceofJsonPrimitive)) { -
throw new JsonParseException( "Thedate );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(( newDate()).getTime()));
- Google GSON GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")不能格式化Data
- Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
- Linux时间(date)格式化(yyyy-mm-dd hh:MM:ss)
- 日期格式化 yyyy-MM-dd HH:mm:ss.fff
- yyyy-MM-dd HH:mm:ss 区别
- YYYY-mm-dd HH:MM:SS
- NSDate YYYY-MM-dd hh:mm:ss
- YYYY-mm-dd HH:MM:SS
- SqlServer yyyy-MM-dd hh:mm:ss
- yyyy-MM-dd HH:mm:ss SSS
- yyyy-MM-dd HH:mm:ss和yyyy-MM-dd hh:mm:ss
- 日期格式化{0:yyyy-MM-dd HH:mm:ss.fff}和{0:yyyy-MM-dd hh:mm:ss.fff}的区别
- 日期格式化{0:yyyy-MM-dd HH:mm:ss.fff}和{0:yyyy-MM-dd hh:mm:ss.fff}的区别
- 日期格式化{0:yyyy-MM-dd HH:mm:ss.fff}和{0:yyyy-MM-dd hh:mm:ss.fff}的区别
- 日期格式化{0:yyyy-MM-dd HH:mm:ss.fff}和{0:yyyy-MM-dd hh:mm:ss.fff}的区别
- 日期格式化{0:yyyy-MM-dd HH:mm:ss.fff}和{0:yyyy-MM-dd hh:mm:ss.fff}的区别
- 日期格式化{0:yyyy-MM-dd HH:mm:ss.fff}和{0:yyyy-MM-dd hh:mm:ss.fff}的区别
- 日期格式化{0:yyyy-MM-dd HH:mm:ss.fff}和{0:yyyy-MM-dd hh:mm:ss.fff}的区别
- [记录]openssl给自己签证cmd过程全记录
- stm32时钟
- 【转】从金融IT公司工作10年后转到银行的工作体会
- hexdump用法
- linux下时间有关的函数和结构体
- Google GSON GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")不能格式化Data
- 2012第二届GIS制图大赛——赛前培训资料(下篇)& 培训资料下载
- C++ 连接数据库
- ubuntu12.10下用gcc4.7.2编译4.6.3,
- impdp数据表table导入
- minicom设置
- vs2008常见调试问题汇总
- eclipse开发velocity实例(初学)
- 字符串的全排列和组合算法