Android · 2018年11月24日 0

Retrofit2 使用FastJson作为Converter

Retortfit2
Retrofit是由Square公司出品的针对于Android和Java的类型安全的Http客户端,网络服务基于OkHttp 。 个人觉得更为准确的说法是,Retrofit是OkHttp的一个包装工具类,可以更加方便的调用Restful API。

Retrofit2 默认提供的Converter
Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire

Simple XML: com.squareup.retrofit2:converter-simplexml

Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

下面就来讲解如何扩展Converter

首先创建FastJsonConverterFactory 类,并继承Converter.Factory,重写其中的responseBodyConverter方法与requestBodyConverter方法。
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class FastJsonConverterFactory extends Converter.Factory{

public static FastJsonConverterFactory create() {
return new FastJsonConverterFactory();
}

/**
* 需要重写父类中responseBodyConverter,该方法用来转换服务器返回数据
*/
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new FastJsonResponseBodyConverter<>(type);
}

/**
* 需要重写父类中responseBodyConverter,该方法用来转换发送给服务器的数据
*/
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return new FastJsonRequestBodyConverter<>();
}

}
创建FastJsonResponseBodyConverter 类

import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;
import retrofit2.Converter;

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 {
BufferedSource bufferedSource = Okio.buffer(value.source());
String tempStr = bufferedSource.readUtf8();
bufferedSource.close();
return JSON.parseObject(tempStr, type);

}
}
创建FastJsonRequestBodyConverter

import com.alibaba.fastjson.JSON;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;

public class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse(“application/json; charset=UTF-8”);

@Override
public RequestBody convert(T value) throws IOException {
return RequestBody.create(MEDIA_TYPE, JSON.toJSONBytes(value));
}
}
使用方法

retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(CustomerOkHttpClient.getClient())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//在此处声明使用FastJsonConverter做为转换器
.addConverterFactory(FastJsonConverterFactory.create())
.build()

 

转自:https://blog.csdn.net/suyimin2010/article/details/79877775

Share this: