retrofit2自定converter要点

接口定义中要写明转换类型 TYNetworkingRespondModel
public class TYNetworkingRespondModel {
    private String Msg;
    private int Code;
    private Map Data;
}
@GET("app/MobileApp.ashx")
    Call createGetRequest(@Query("Module") String module,@Query("Param") String param);
自定义Factory中处理转换
public class MyConverterFactory extends Converter.Factory {
    public static MyConverterFactory create() {
        return create(new Gson());
    }

    private final Gson gson;

    public static MyConverterFactory create(Gson gson) {
        return new MyConverterFactory(gson);
    }

    private MyConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }

//    @javax.annotation.Nullalbe
    @Override
    public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        TypeAdapter adapter = gson.getAdapter(TypeToken.get(type));
        //判断响应实体类型是否是我们需要特殊处理的特殊类型(此处以String类型)
        if (type == TYNetworkingRespondModel.class) {
            //创建xxConverter来 进行特殊转换
            return new MyResponseConverter(gson);
        } else {
            //其它类型我们不处理,返回null就行 会交给后面的解析器来解析
            return null;
        }
    }

    private class MyResponseConverter implements Converter {
        private final Gson gson;

        MyResponseConverter(Gson gson) {
            this.gson = gson;
        }

        @Override
        public T convert(ResponseBody value) throws IOException {
            //在此处进行我们的转换
            String response = value.string();
            TYNetworkingRespondModel movieDataBean = gson.fromJson(response, TYNetworkingRespondModel.class);
//            return (T) response;
            return (T) movieDataBean;
        }

    }
}
具体使用
Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(TYStaticDefine.STR_BASE_URL)
                    .addConverterFactory(MyConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
更复杂的转化可以通过自定义JsonDeserializer实现

详情见:http://www.javacreed.com/gson-deserialiser-example/

你可能感兴趣的:(retrofit2自定converter要点)