retrofit 结合GSON格式化时间问题

xierfly 2017-02-21 02:16:46
刚接触java不久,看到有一个retrofit,翻阅了很多文章,发现都没有对时间格式化的说明。我的问题主要涉及到的是 addConverterFactory(GsonConverterFactory.create(gsonFormat)); --- 这个是在什么时候起作用?

背景描述:
private static final Gson gsonFormat = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
public static void main(String[] args) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:31293/")
.addConverterFactory(GsonConverterFactory.create(gsonFormat))
.build();

UserService service = retrofit.create(UserService.class);

try {
Call<UserBean> info;
info = service.profile("1", new Date());

Response<UserBean> resp = info.execute();

if (!resp.isSuccessful() || resp.code() != 200) {
System.out.println("error:resp.code is :" + resp.code());
return;
}

UserBean userInfo = resp.body();

System.out.println(String.format("userInfo.getUserName={%s}", userInfo.getUserName()));

System.out.println(gsonFormat.toJson(userInfo)); // 这里我是手动调用了gsonFormat 才输出 这样的 {"userId":1,"userName":"aaa","age":30,"sex":1,"createTime":"2017-02-20"}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}

创建的实体是:
public class UserBean {
private int userId;
private String userName;
private int age;
private byte sex;
private Date createTime;
// get set 省略
}

定义接口:

public interface UserService {

@GET("api/user/{userId}")
Call<UserBean> profile(@Path("userId") String userId, @Query("testDate") Date dt);
}

问题:
1、addConverterFactory(GsonConverterFactory.create(gsonFormat)); --- 这个是在什么时候起作用?
2、如何返回一个指定格式化的时间字段;
...全文
285 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
注意:本项目使用android studio开发,eclipse可能无法直接使用。 本项目是PHPHub 社区非官方 Android 客户端, App UI 风格遵循了 Google Material Design 设计风格, 项目架构使用了 MVP 模式, 数据处理使用了 RxJava Retrofit 技术。 项目特点: 界面设计遵循 Google 设计规范 沉浸式状态栏 数据处理使用了 RxJava Retrofit 二维码扫码登录 WebView 图片点击事件 JS 注入 项目架构使用 MVP 模式 发布帖子支持使用 Markdown 语法编辑器 多主题切换 运行环境: Min Android SDK version 4.0 Android Studio 2.2.1 Gradle version 2.14.1 Gradle plugin version 2.2.1 Build tools version 24.0.2 使用到开源库: 项目名称 简介 Logger 一个强大漂亮的Log输出日志,支持json格式化输出 Material-Dialogs 一个强大漂亮的Material Dialog BGABadgeView-Android Android徽章控件 MultiStateView 通用显示各种状态 View FloatingActionButton 悬浮操作按钮库, 支持监听滑滚动事件 glide-transformations 快速实现毛玻璃效果 writeily-pro Markdown 文本编辑 Demo RxJava RxJava RxAndroid RxAndroid Retrofit Retrofit Gson Json 解析库 Prettytime 格式化日期时间 barcodescanner 二维码扫描 fresco Facebook 开源的图片缓存库 butterknife 注解框架 materialish-progress Material Design 风格进度条 PhotoDraweeView 基于 Fresco 的图片缩放控件 cwac-anddown Markdown 渲染 gm-mkdroid 一个所见即所得的 Markdown 编辑器 android-Ultra-Pull-To-Refresh-With-Load-More 这个是基于 Ultra-Pull-to-Refresh 库修改增加支持加载更多的刷新控件 T-MVP 泛型深度解耦下的MVP大瘦身 本项目git地址:https://github.com/Freelander/Elephant

50,523

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧