42 lines
1.1 KiB
Java
42 lines
1.1 KiB
Java
package com.yutou.nas.okhttp.converter;
|
|
|
|
import com.alibaba.fastjson2.JSONObject;
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.TypeAdapter;
|
|
import com.yutou.nas.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<T> implements Converter<ResponseBody, T> {
|
|
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<T> body;
|
|
try {
|
|
body = JSONObject.parseObject(string, type);
|
|
body.setSrc(string);
|
|
return (T) body;
|
|
} catch (Exception e) {
|
|
body = new HttpBody();
|
|
body.setSrc(string);
|
|
}
|
|
return (T) body;
|
|
|
|
}
|
|
} |