很多時(shí)候在開(kāi)發(fā)過(guò)程中需要對(duì)接口進(jìn)行測(cè)試纺裁,查看接口返回?cái)?shù)據(jù)是否正確
數(shù)據(jù)格式為:
{"status":1,"info":"","data":{"cate_product":{"0":{"..."}}}}
在項(xiàng)目中使用了 Retrofit2+Rxjava2的形式來(lái)請(qǐng)求數(shù)據(jù)
為了測(cè)試接口的使用采用了Observable<BaseResult<String>>
的形式返回?cái)?shù)據(jù),BaseResult類(lèi)如下:
public class BaseResult<T> {
public static final int SUCCESS = 1;
private int status;
private String info;
private T data;
public boolean isSuccess() {
return (status == SUCCESS);
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
使用GsonConverter 則會(huì)出現(xiàn)如下的異常
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 31 path $.data
但是在某些情況下需要手動(dòng)解析,只需要String類(lèi)型
解決方案就是使用自定義的FastJsonConvert 使用FastJson來(lái)解析數(shù)據(jù)
public class FastJsonConvertFactory extends Converter.Factory {
public static FastJsonConvertFactory create(){
return new FastJsonConvertFactory();
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new FastJsonResponseBodyConverter<>(type);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return new FastJsonRequestBodyConverter();
}
}
public class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
public static final Charset UTF_8= Charset.forName("UTF-8");
public static final MediaType type= MediaType.parse("application/json; charset=UTF-8");
@Override
public RequestBody convert(T value) throws IOException {
return RequestBody.create(type, JSON.toJSONString(value).getBytes("UTF-8"));
}
}
public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody,T> {
public static final Charset UTF_8=Charset.forName("UTF-8");
private Type type;
public FastJsonResponseBodyConverter(Type type){
this.type=type;
}
@Override
public T convert(ResponseBody value) throws IOException {
InputStreamReader inputStreamReader;
BufferedReader reader;
inputStreamReader=new InputStreamReader(value.byteStream(),UTF_8);
reader=new BufferedReader(inputStreamReader);
StringBuilder sb=new StringBuilder();
String line;
if((line=reader.readLine())!=null){
sb.append(line);
}
inputStreamReader.close();
reader.close();
return JSON.parseObject(sb.toString(),type);
}
}
使用
Retrofit retrofit = new Retrofit.Builder().baseUrl(Contacts.BASE_URL)
.addConverterFactory(FastJsonConvertFactory.create()) //使用自定義的Converter
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient)
.build();