改造GSON将日期从json字符串序列化为java.util.date [英] Retrofit GSON serialize Date from json string into java.util.date

查看:706
本文介绍了改造GSON将日期从json字符串序列化为java.util.date的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的REST调用使用了Retrofit库。我所做的大部分工作都很流畅,但由于某种原因,我遇到了将JSON时间戳字符串转换为 java.util.Date 对象的问题。即将到来的JSON看起来像这样。

  {
date:2013-07-16,
created_at: 2013-07-16T22:52:36Z,
}

如何告诉改造或Gson将这些字符串转换为 java.util.Date对象

解决方案

< pre $ Gson gson = new GsonBuilder()
.setDateFormat(yyyy-MM-dd'T'HH:mm:ss)
.create();

RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_BASE_URL)
.setConverter(new GsonConverter.create(gson))
.build();

您可以设置自定义的Gson解析器进行翻新。更多信息:改造网站



<看看Ondreju的反应,看看如何在改造2 / b
中实现这一点

I am using the Retrofit library for my REST calls. Most of what I have done has been smooth as butter but for some reason I am having issues converting JSON timestamp strings into java.util.Date objects. The JSON that is coming in looks like this.

{
    "date": "2013-07-16",
    "created_at": "2013-07-16T22:52:36Z",
} 

How can I tell Retrofit or Gson to convert these strings into java.util.Date objects?

解决方案

Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.create();

RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_BASE_URL)
.setConverter(new GsonConverter.create(gson))
.build();

You can set your customized Gson parser to retrofit . More here: Retrofit Website

Look at Ondreju's response to see how to implement this in retrofit 2

这篇关于改造GSON将日期从json字符串序列化为java.util.date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆