Retrofit2的基础使用请参考Java Retrofit2使用
自定义Converter(转换器)
retrofit默认情况下支持的converts有Gson,Jackson,Moshi...
- 搭建基础架构
这里将自定义一个FastJsonConverterFactory来解析返回的数据,其内部使用阿里巴巴的Fastjson(依赖添加compile 'com.alibaba:fastjson:1.2.37'
)。
首先要搭建好Retrofit2的使用架构,其次在创建Retrofit实例的时候添加一个
// 3. 获取实例
Retrofit retrofit = new Retrofit.Builder()
// 设置OKHttpClient,如果不设置会提供一个默认的
.client(new OkHttpClient())
//设置baseUrl
.baseUrl(url)
//添加Gson转换器
.addConverterFactory(FastJsonConverterFactory.create())
.build();
- 创建继承与Converter.Factory的FastJsonConverterFactory类,并实现create(),requestBodyConverter(),responseBodyConverter()方法。
/**
* fastjson解析工厂
* @author mazaiting
*/
public class FastJsonConverterFactory extends Converter.Factory{
public static Factory create() {
return new FastJsonConverterFactory();
}
@Override
public Converter<Info, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
Annotation[] methodAnnotations, Retrofit retrofit) {
return new FastJsonRequestConverter();
}
@Override
public Converter<ResponseBody, Info> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new FastJsonResponseConverter(type);
}
}
- 实现FastJsonRequestConverter类
/**
* 请求转换类,将Info对象转化为RequestBody对象
* @author mazaiting
*/
public class FastJsonRequestConverter implements Converter<Info, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private static final Charset UTF_8 = Charset.forName("UTF-8");
public FastJsonRequestConverter() {
}
public RequestBody convert(Info value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
writer.write(value.toString());
writer.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
- 实现FastJsonResponseConverter类
/**
* fastjson响应转换器,将ResponseBody对象转化为Info对象
* @author Administrator
*
*/
public class FastJsonResponseConverter implements Converter<ResponseBody, Info> {
/**
* 反射类型
*/
private Type type;
public FastJsonResponseConverter(Type type) {
this.type = type;
}
public Info convert(ResponseBody value) throws IOException {
try {
/**
* fastjson解析数据
* 此处特别注意: Info应为外部类,并将其类中的成员设置为public,
* 否则会无法创建Info对象,从而导致解析异常
*/
Info info = JSON.parseObject(value.string(), type);
System.out.println(info);
return info;
} finally {
value.close();
}
}
}