使用Retrofit +Gson 的时候遇到的问题

2017-08-16  本文已影响162人  写代码的解先生

很多时候在开发过程中需要对接口进行测试,查看接口返回数据是否正确

数据格式为:

{"status":1,"info":"","data":{"cate_product":{"0":{"..."}}}}

在项目中使用了 Retrofit2+Rxjava2的形式来请求数据
为了测试接口的使用采用了Observable<BaseResult<String>> 的形式返回数据,BaseResult类如下:

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 则会出现如下的异常

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 31 path $.data

但是在某些情况下需要手动解析,只需要String类型

解决方案就是使用自定义的FastJsonConvert 使用FastJson来解析数据

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();
上一篇下一篇

猜你喜欢

热点阅读