Android之Retrofit2.0 處理返回json報文並轉換成bean物件

lvxiangan發表於2018-09-01

本文主要介紹在Retrofit 2.0中,如何將伺服器返回的json字串轉換成bean物件。

 

參考部落格:

實現效果:

      enter image description here

使用姿勢:

   1. 使用教程

  • 新增依賴 
    • compile ‘com.squareup.retrofit2:retrofit:2.2.0’
    • compile ‘com.squareup.retrofit2:converter-gson:2.2.0’
  • AndroidStudio新增Gson外掛——GsonFormat

   2. 使用API

  • 所用api:http://www.mrsorrow.xin/pro/rank_querySpecRankByUniv?university.univCode=10280&page=1
  • 功能:根據高校程式碼進行學科專業類排名
  • 返回json如下:

    {
        "rows": [
            {
                "id": 1893,
                "specCode": "",
                "specName": "冶金工程類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "5",
                "univScore": "78"
            },
            {
                "id": 328,
                "specCode": "0303",
                "specName": "社會學類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "8",
                "univScore": "77"
            },
            {
                "id": 828,
                "specCode": "0503",
                "specName": "新聞傳播學類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "10",
                "univScore": "77"
            },
            {
                "id": 3959,
                "specCode": "1303",
                "specName": "戲劇與影視學類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "4",
                "univScore": "77"
            },
            {
                "id": 396,
                "specCode": "0305",
                "specName": "馬克思主義理論類",
                "univCode": "10280",
                "univName": "上海大學",
                "univRank": "17",
                "univScore": "76"
            }
        ]
    }
    

   3. 入門使用Retrofit

  • 定義介面(封裝URL地址和資料請求) :

    @GET("rank_querySpecRankByUniv")
    Call<ResponseBody> querySpecRankByUniv(
            @Query("university.univCode") String univCode,
            @Query("page") int page);
    
  • 例項化Retrofit:

    Retrofit retrofit = new Retrofit.Builder()
             .baseUrl(Constant.BASE_URL)
             .build();
    
  • 通過Retrofit例項建立介面服務物件

    QueryRankService service = retrofit.create(QueryRankService.class);
    
  • ResponseBody中存放著我們請求的資料,呼叫response.body().string()轉化為字串:

     Call<ResponseBody> call = service.querySpecRankByUniv("10280", 1);
     call.enqueue(new Callback<ResponseBody>() {
         @Override
         public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
             if(response.isSuccessful()){
                 try {
                     String result = response.body().string();
                     mTextView.setText(result);
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
    
         @Override
         public void onFailure(Call<ResponseBody> call, Throwable t) {
    
         }
     });
    

   4. 使用GsonFormat生成Bean

  • 新建Bean類——SpecRank.java
  • 類中右鍵Generate–》GsonFormat,將json樣例拷貝進AS,點選ok即可
  • 生成如下:

   5. 使用Gson解析

  • 定義介面(封裝URL地址和資料請求) :

    @GET("rank_querySpecRankByUniv")
        Call<SpecRankBean> querySpecRankByUnivUseGson(
                @Query("university.univCode") String univCode,
                @Query("page") int page);
    
  • 例項化Retrofit:

    Retrofit retrofit = new Retrofit.Builder()
                     .baseUrl(Constant.BASE_URL)
                     .addConverterFactory(GsonConverterFactory.create())
                     .build();
    
  • 將請求的資料可以直接轉換為我們的Bean,通過各種get方法獲取我們想要的資料:

    call.enqueue(new Callback<SpecRankBean>() {
         @Override
         public void onResponse(Call<SpecRankBean> call, Response<SpecRankBean> response) {
             if(response.isSuccessful()){
                 SpecRankBean bean = response.body();
                 List<SpecRankBean.RowsBean> list = bean.getRows();
                 String result = "";
                 for (SpecRankBean.RowsBean rowsBean : list) {
                     result += rowsBean.getUnivName() + rowsBean.getSpecName() + "\n";
                 }
                 mTextView.setText(result);
             }
         }
    
         @Override
         public void onFailure(Call<SpecRankBean> call, Throwable t) {
    
         }
     });
    

 

轉自:https://blog.csdn.net/bskfnvjtlyzmv867/article/details/70667041

相關文章