blog,blog,blog
blog,blog,blog使用FastJson 解析 Retrofit2 返回结果
Retrofit提供的Converter
Converter | Gradle依赖 |
---|---|
Gson | com.squareup.retrofit2:converter-gson:2.0.2 |
Jackson | com.squareup.retrofit2:converter-jackson:2.0.2 |
Moshi | com.squareup.retrofit2:converter-moshi:2.0.2 |
Protobuf | com.squareup.retrofit2:converter-protobuf:2.0.2 |
Wire | com.squareup.retrofit2:converter-wire:2.0.2 |
Simple XML | com.squareup.retrofit2:converter-simplexml:2.0.2 |
Scalars |
com.squareup.retrofit2:converter-scalars:2.0.2 |
我们为Fastjson定义一个Converter。
import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Converter; import retrofit2.Retrofit;import java.lang.annotation.Annotation;
import java.lang.reflect.Type;/**
-
Created by Eddie on 2017/4/4.
*/
public class FastJsonConverterFactory extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, final Retrofit retrofit) {
return new FastJsonResponseBodyConverter(type);}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {return new FastJsonRequestBodyConverter();
}
}
import com.alibaba.fastjson.JSON; import okhttp3.MediaType; import okhttp3.RequestBody; import retrofit2.Converter;import java.io.IOException;
/**
-
Created by Eddie on 2017/4/5.
*/
public class FastJsonRequestBodyConverter<T> implements Converter< T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");public FastJsonRequestBodyConverter() {
}@Override
public RequestBody convert(T value) throws IOException {return RequestBody.create(MEDIA_TYPE, JSON.toJSONString(value));
}
}
import com.alibaba.fastjson.JSON; import okhttp3.ResponseBody; import retrofit2.Converter;import java.io.IOException;
import java.lang.reflect.Type;/**
-
Created by Eddie on 2017/4/4.
*/
public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Type type;public FastJsonResponseBodyConverter(Type type) {
this.type = type;}
@Override
public T convert(ResponseBody value) throws IOException {
return JSON.parseObject(value.string(), type);
}
}