★43.Retrofit + Gson

簡介

  • 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ù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,992評論 19 139
  • 相信很多人都在使用Retrofit,我也在用,但是對它的理解都不是太深刻,現(xiàn)在Retrofit2已經(jīng)出來一段時(shí)間,...
    WHOKNOWME閱讀 7,554評論 6 19
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,558評論 25 708
  • 我早上給她發(fā)了個(gè)早,但是她沒回,剛才我看了一下微信,她的微信步數(shù)只有16但是有個(gè)人已經(jīng)點(diǎn)贊了,微信步數(shù)是從多到少排...
    愛她的我閱讀 131評論 0 0
  • 1、今天上班任務(wù)不多,很快做完,現(xiàn)在需要反思這一個(gè)月的工作。效率提升的太慢,還是自己對代碼熟悉程度不高,空閑時(shí)間多...
    任雨點(diǎn)閱讀 104評論 0 0