简介
-
Gson Converter官网。
- 注意到 Retrofit 所有的接口定义都是返回
Call<ResponseBody>
,但是其实可以是别的类型,比如Call<Blog>
,这需要相应的Converter
。
反序列化示例(Json字符串->Model对象)
1. 定义Model
public interface BlogService {
@GET("blog/{id}")
Call<Blog> getFirstBlog(@Path("id") int id);
}
2. 创建Gson
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd hh:mm:ss")
.create();
3. 创建Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:4567/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
4. 创建Model
BlogService service = retrofit.create(BlogService.class);
5. 创建Call
Call<Blog> call = service.getBlog(2);
6. 执行Call
call.enqueue(new Callback<Blog>() {
@Override
public void onResponse(Call<Blog> call, Response<Blog> response) {
// 已经转换为想要的类型了
Blog result = response.body();
System.out.println(result);
}
@Override
public void onFailure(Call<Blog> call, Throwable t) {
t.printStackTrace();
}
});
序列化示例(Model对象->Json字符串)
1. 定义Model
public interface BlogService {
@POST("blog")
Call<Blog> createBlog(@Body Blog blog);
}
2. 构建Gson
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd hh:mm:ss")
.create();
3. 构建Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:4567/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
4. 创建Model
BlogService service = retrofit.create(BlogService.class);
5. 创建Call
Blog blog = new Blog();
blog.content = "新建的Blog";
blog.title = "测试";
blog.author = "name";
Call<Blog> call = service.createBlog(blog);
6. 执行Call
call.enqueue(new Callback<Blog>() {
@Override
public void onResponse(Call<Blog> call, Response<Blog> response) {
// 已经转换为想要的类型了
Blog result = response.body();
System.out.println(result);
}
@Override
public void onFailure(Call<Blog> call, Throwable t) {
t.printStackTrace();
}
});