package com.yutou.okhttp.converter; import com.alibaba.fastjson2.JSONObject; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.yutou.okhttp.HttpBody; import okhttp3.ResponseBody; import org.jetbrains.annotations.Nullable; import retrofit2.Converter; import java.io.IOException; import java.lang.reflect.Type; public class JsonResponseBodyConverter implements Converter { Gson gson; TypeAdapter adapter; Type type; public JsonResponseBodyConverter(Gson gson, TypeAdapter adapter, Type type) { this.gson = gson; this.adapter = adapter; this.type = type; } @Nullable @Override public T convert(ResponseBody responseBody) throws IOException { String string = new String(responseBody.bytes()); responseBody.close(); HttpBody body; try { body = JSONObject.parseObject(string, type); if(body.getData()==null){ JSONObject jt=JSONObject.parseObject(JSONObject.toJSONString(new HttpBody<>())); jt.put("data",JSONObject.parseObject(string)); HttpBody bt=JSONObject.parseObject(jt.toJSONString(),type); body.setData(bt.getData()); } body.setSrc(string); return (T) body; } catch (Exception e) { e.printStackTrace(); try { body = new HttpBody<>(); body.setData(JSONObject.parseObject(string, type)); body.setSrc(string); } catch (Exception e2) { e2.printStackTrace(); body = new HttpBody<>(); body.setSrc(string); } } return (T) body; } }