80,351
社区成员
发帖
与我相关
我的任务
分享
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
public final class JsonConverterFactory extends Converter.Factory {
public static JsonConverterFactory create() {
return new JsonConverterFactory();
}
private final Gson gson;
private JsonConverterFactory() {
this.gson = new Gson();
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return value -> {
String json = value.string();
Type resultType = new TypeToken<Result<IpInfo>>() {}.getType();
Result<IpInfo> result = gson.fromJson(json, resultType);
if (result.code == 0) {
return result.data;
}
else {
throw new RuntimeException("code: " + result.code);
}
};
}
}
public final class Result<T> {
public int code;
public T data;
}
Type resultType = new TypeToken<Result<IpInfo>>() {}.getType();
public final class JsonConverterFactory extends Converter.Factory {
public static JsonConverterFactory create() {
return new JsonConverterFactory();
}
private final Gson gson;
private JsonConverterFactory() {
this.gson = new Gson();
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return value -> {
String json = value.string();
Type resultType = new ParameterizedType() {
@Override
public Type[] getActualTypeArguments() {
return new Type[] { type };
}
@Override
public Type getRawType() {
return Result.class;
}
@Override
public Type getOwnerType() {
return null;
}
};
Result result = gson.fromJson(json, resultType);
if (result.code == 0) {
return result.data;
}
else {
throw new RuntimeException("code: " + result.code);
}
};
}
}