Java Retrofit2 use -- custom converter

Keywords: Java Retrofit JSON

For the basic use of Retrofit2, please refer to Java Retrofit2 uses

Custom converter
By default, the supported conversions of retrofit are Gson,Jackson,Moshi

  1. Build infrastructure
    Here, we will customize a FastJsonConverterFactory to parse the returned data, which internally uses Alibaba's fastjson (depends on adding compile 'com.alibaba:fastjson:1.2.37').
    First, we need to build the use architecture of Retrofit2, and then add an instance of Retrofit2 when creating an instance
        // 3. Get an example
        Retrofit retrofit = new Retrofit.Builder()
                // Set OKHttpClient. If it is not set, a default
                .client(new OkHttpClient())
                //Set baseUrl
                .baseUrl(url)
                //Add Gson converter
                .addConverterFactory(FastJsonConverterFactory.create())
                .build();
  1. Create the FastJsonConverterFactory class inherited from Converter.Factory, and implement the create(), requestBodyConverter(),responseBodyConverter().
/**
 * fastjson Analytic factory
 * @author mazaiting
 */
public class FastJsonConverterFactory extends Converter.Factory{

    public static Factory create() {
        return new FastJsonConverterFactory();
    }
    
    @Override
    public Converter<Info, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
            Annotation[] methodAnnotations, Retrofit retrofit) {
        return new FastJsonRequestConverter();
    }
    
    
    @Override
    public Converter<ResponseBody, Info> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new FastJsonResponseConverter(type);
    }

}
  1. Implement FastJsonRequestConverter class
/**
 * Request conversion class, converting Info object to RequestBody object
 * @author mazaiting
 */
public class FastJsonRequestConverter implements Converter<Info, RequestBody> {
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    public FastJsonRequestConverter() {
    }

    public RequestBody convert(Info value) throws IOException {
        Buffer buffer = new Buffer();
        Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
        writer.write(value.toString());
        writer.close();         
        return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
    }

}
  1. Implement FastJsonResponseConverter class
/**
 * fastjson Response converter, converting ResponseBody object to Info object
 * @author Administrator
 *
 */
public class FastJsonResponseConverter implements Converter<ResponseBody, Info> {
    /**
     * Reflection type
     */
    private Type type;
    public FastJsonResponseConverter(Type type) {
        this.type = type;
    }

    public Info convert(ResponseBody value) throws IOException {
        try {
            /**
             * fastjson Analytical data
             * Special note here: Info should be an external class and its members in the class should be set to public,
             * Otherwise, the Info object cannot be created, resulting in parsing exception
             */
            Info info = JSON.parseObject(value.string(), type);
            System.out.println(info);
            return info;
        } finally {
            value.close();
        }
    }

}

Posted by Memphis10 on Wed, 11 Dec 2019 07:42:17 -0800