retrofit 结合GSON格式化时间问题
刚接触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、如何返回一个指定格式化的时间字段;