Retrofit 自定义Converter实现发送String和接收JSON

Retrofit已经为用户提供了六种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

但最近项目要求,发送时String,接收JSON,当前的Converter设置后,都是同时针对发送和接收,因此我们需要自定义Converter。不过如上的Converter已经有String和JSON的处理方式,我们可以组合 com.squareup.retrofit2:converter-gson和com.squareup.retrofit2:converter-scalars,从而实现项目要求。

 

请求的字符串转换:

public class StringRequestBodyConverter implements Converter {

    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain; charset=UTF-8");

    StringRequestBodyConverter() {
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        return RequestBody.create(MEDIA_TYPE, String.valueOf(value));
    }



}

响应的JSON转换:

public class JsonResponseBodyConverter implements Converter {

    private final Gson gson;
    private final TypeAdapter adapter;

    JsonResponseBodyConverter(Gson gson, TypeAdapter adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try {
            return adapter.read(jsonReader);
        } finally {
            value.close();
        }
    }


}

Converter的实现工厂:

public class ExtConverterFactory extends Converter.Factory{

    private final Gson gson;


    public static ExtConverterFactory create() {
        return new ExtConverterFactory(new Gson());
    }

    private ExtConverterFactory(Gson gson) {
        this.gson = gson;
    }

    @Override
    public Converter responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        TypeAdapter adapter = gson.getAdapter(TypeToken.get(type));
        return new JsonResponseBodyConverter<>(gson, adapter);
    }

    @Override
    public Converter requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        if (type == String.class
                || type == boolean.class
                || type == Boolean.class
                || type == byte.class
                || type == Byte.class
                || type == char.class
                || type == Character.class
                || type == double.class
                || type == Double.class
                || type == float.class
                || type == Float.class
                || type == int.class
                || type == Integer.class
                || type == long.class
                || type == Long.class
                || type == short.class
                || type == Short.class) {
            return new StringRequestBodyConverter();
        }
        return null;

    }

}

之后就能初始化Retrofit如下,从而实现发送String,接收JSON

 Retrofit  retrofit = new Retrofit.Builder()
                .addConverterFactory(ExtConverterFactory.create())
                .client(new OkHttpClient())
                .baseUrl("http://api.test.com/")
                .build();


  NetApi netApi = retrofit.create(NetApi.class);

 

 

 

 

参考文档:https://square.github.io/retrofit/

你可能感兴趣的:(Android)