retrofit 结合GSON格式化时间问题

xierfly xierfly 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
刚接触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、如何返回一个指定格式化的时间字段;
...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
xierfly
Java 51,407 成员 86,172 内容