簡介
-
Gson Converter官網(wǎng)。
- 注意到 Retrofit 所有的接口定義都是返回
Call<ResponseBody>
,但是其實(shí)可以是別的類型,比如Call<Blog>
,這需要相應(yīng)的Converter
。
反序列化示例(Json字符串->Model對象)
1. 定義Model
public interface BlogService {
@GET("blog/{id}")
Call<Blog> getFirstBlog(@Path("id") int id);
}
2. 創(chuàng)建Gson
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd hh:mm:ss")
.create();
3. 創(chuàng)建Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:4567/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
4. 創(chuàng)建Model
BlogService service = retrofit.create(BlogService.class);
5. 創(chuàng)建Call
Call<Blog> call = service.getBlog(2);
6. 執(zhí)行Call
call.enqueue(new Callback<Blog>() {
@Override
public void onResponse(Call<Blog> call, Response<Blog> response) {
// 已經(jīng)轉(zhuǎn)換為想要的類型了
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. 構(gòu)建Gson
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd hh:mm:ss")
.create();
3. 構(gòu)建Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:4567/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
4. 創(chuàng)建Model
BlogService service = retrofit.create(BlogService.class);
5. 創(chuàng)建Call
Blog blog = new Blog();
blog.content = "新建的Blog";
blog.title = "測試";
blog.author = "name";
Call<Blog> call = service.createBlog(blog);
6. 執(zhí)行Call
call.enqueue(new Callback<Blog>() {
@Override
public void onResponse(Call<Blog> call, Response<Blog> response) {
// 已經(jīng)轉(zhuǎn)換為想要的類型了
Blog result = response.body();
System.out.println(result);
}
@Override
public void onFailure(Call<Blog> call, Throwable t) {
t.printStackTrace();
}
});
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。