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、如何返回一个指定格式化的时间字段;
...全文
298 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

51,397

社区成员

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

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