retrofit2.0中自定義轉換器使用,通用啊

1、自定義轉換:
說白了,就是把請求服務器獲取的數據轉換成自定義的object對象,
比如 Student、Teacher …
通常是轉換json數據,
並且已經自帶了一些轉換器,
默認是

Response<ResponseBody> 
response類型,可以理解成string類型

我的需求是將json數據解析成

List<Data>

public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {}
沒有用轉換器之前我的代碼對返回數據解析:

 call.enqueue(new Callback<ResponseBody>() {

            @Override
            public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                Log.d("lihui", "123onResponse");
                try {
                    ResponseBody httpResult = response.body();
                    //原始數據下手
                    String result = httpResult.string();
                    org.json.JSONObject jsonObject = new org.json.JSONObject(result);
                    String reason = jsonObject.getString("reason");
                    ToastUtils.setToastText(context, reason);
                    String result2 = jsonObject.getString("result");
                    org.json.JSONObject jsonObject2 = new org.json.JSONObject(result2);
                    String stat = jsonObject2.getString("stat");
                    String data = jsonObject2.getString("data");
                    org.json.JSONArray jsonArray2 = new org.json.JSONArray(data);
                    list.clear();
                    for (int i = 0; i < jsonArray2.length(); i++) {
                        //獲取每一個JsonObject對象
                        org.json.JSONObject myjObject = jsonArray2.getJSONObject(i);
                        if (myjObject != null) {
                            Data data1 = new Data(myjObject);
                            Log.d("lihui", "Fragment onResponse getUniquekey---" + data1.getUniquekey());
                            Log.d("lihui", "Fragment onResponse data---" + data1);
                            list.add(data1);
                        }
                    }
                    if (list != null && list.size() > 0 && mHandler != null) {
                        Message msg = mHandler.obtainMessage();
                        msg.what = 0;
                        msg.obj = list;
                        mHandler.sendMessage(msg);
                        empty.setVisibility(View.GONE);
                        cacheMap.put(type, list);
                    }
                    Log.d("lihui", "159 list---" + list);

                } catch (Exception e) {
                    Log.d("lihui", "114e---" + e.getMessage());
                    pullToRefreshRecyclerView.onRefreshComplete();
                }
}

2、添加轉換器
就是在返回數據之後,多出一步驟,就是自動轉換成你返回的類型。
方法:
1)
修改返回類型接口

public interface  HttpService {

    @POST("toutiao/index")
    Call<List<Data>> getData(@Query("type") String type, @Query("key") String key);
}

2)修改返回類型
retrofit.Call

static class CustomConverterFactory extends Converter.Factory {
        static CustomConverterFactory factory;

        public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
            Log.d("CustomConverterFactory", "type---" + type);
            return new UserResponseConverter(type);
        }

        public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
            return null;
        }

        public static CustomConverterFactory create() {
            if (factory == null) {
                factory = new CustomConverterFactory();
            }
            return factory;
        }
    }

4)自定義Converter

 public static class UserResponseConverter<T> implements Converter<ResponseBody, T> {
        private Type type;

        public UserResponseConverter(Type type) {
            this.type = type;
        }

        @Override
        public T convert(ResponseBody responseBody) throws IOException {
            List<Data> list = new ArrayList<>();
            //原始數據下手
            String result = responseBody.string();
            //構造1
            try {
                org.json.JSONObject jsonObject = null;
                jsonObject = new org.json.JSONObject(result);
                String reason = jsonObject.getString("reason");
                //  ToastUtils.setToastText(context, reason);
                String result2 = jsonObject.getString("result");
                //構造2
                org.json.JSONObject jsonObject2 = new org.json.JSONObject(result2);
                String stat = jsonObject2.getString("stat");
                String data = jsonObject2.getString("data");
                //構造3
                org.json.JSONArray jsonArray2 = new org.json.JSONArray(data);
                for (int i = 0; i < jsonArray2.length(); i++) {
                    //獲取每一個JsonObject對象
                    org.json.JSONObject myjObject = jsonArray2.getJSONObject(i);
                    if (myjObject != null) {
                        Data data1 = new Data(myjObject);
                        Log.d("lihui", "Fragment onResponse getUniquekey---" + data1.getUniquekey());
                        Log.d("lihui", "Fragment onResponse data---" + data1);
                        list.add(data1);
                    }
                }
                Log.d("CustomConverterFactory", "list---" + list);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return (T) list;
        }
    }

5) 構造時候加入自定義轉換器

  //1

        Retrofit retrofit = new Retrofit.Builder().
                baseUrl("http://v.juhe.cn/").
                addConverterFactory(CustomConverterFactory.create()).build();

        //2
        HttpService myService = retrofit.create(HttpService.class);
        //3
        retrofit.Call<List<Data>> call = myService.getData(type, "9f3097f4cbe47e8abb01ca3b92e49cda");

6)執行請求時候簡單了,直接返回自定義的數據類型

    call.enqueue(new Callback<List<Data>>() {

            @Override
            public void onResponse(Response<List<Data>> response, Retrofit retrofit) {
                Log.d("lihui", "123onResponse");
                try {
                    List<Data> dataList = response.body();
                    Utils.resetList(list, dataList);//交換數據
                    Log.d("CustomConverterFactory", "  Utils.resetList(list, dataList)---" + list);

                    if (list != null && list.size() > 0 && mHandler != null) {
                        Message msg = mHandler.obtainMessage();
                        msg.what = 0;
                        msg.obj = list;
                        mHandler.sendMessage(msg);
                        empty.setVisibility(View.GONE);
                        cacheMap.put(type, list);
                    }
                    Log.d("lihui", "159 list---" + list);

                } catch (Exception e) {
                    Log.d("lihui", "114e---" + e.getMessage());
                    pullToRefreshGridView.onRefreshComplete();
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.d("lihui", "165t:" + t.getMessage());
                t.printStackTrace();
                Message msg = mHandler.obtainMessage();
                msg.what = 1;
                msg.obj = type;
                mHandler.sendMessage(msg);
            }

        });

就是這麼簡單。。。

發佈了49 篇原創文章 · 獲贊 49 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章