Retrofit使用FastJson

介绍

Retrofit 默认提供了gson和Jackson对应的converter,但是并没有提供fastjson转换。在参考了源码的基础之上对fastjson的使用进行简单介绍。

源码分析

在此,我选择了gson转换的三个类GsonConverterFactory,GsonRequestBodyConverter,GsonResponseBodyConverter

  • 首先GsonConverterFactory类:
    该类主要是将GsonRequestBodyConverter,GsonResponseBodyConverter整合到一起,后面使用的时候直接调用该类即可。
public final class GsonConverterFactory extends Converter.Factory {
 public static GsonConverterFactory create() {
   return create(new Gson());
 }

 @SuppressWarnings("ConstantConditions")
 public static GsonConverterFactory create(Gson gson) {
   if (gson == null) throw new NullPointerException("gson == null");
   return new GsonConverterFactory(gson);
 }
 private final Gson gson;
 private GsonConverterFactory(Gson gson) {
   this.gson = gson;
 }
 @Override
 public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
     Retrofit retrofit) {
   TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
   return new GsonResponseBodyConverter<>(gson, adapter);
 }
 @Override
 public Converter<?, RequestBody> requestBodyConverter(Type type,
     Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
   TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
   return new GsonRequestBodyConverter<>(gson, adapter);
 }
}
  • 参考得到FastJsonConverterFactory:这里也是整合作用,不同于gson,fastjson需要以序列化的方式转换。gson也可以使用序列化,这里使用TypeAdapter适配器可以提高效率。
 public class FastJsonConverterFactory extends Converter.Factory {

    private ParserConfig mParserConfig = ParserConfig.getGlobalInstance();
    private int featureValues = JSON.DEFAULT_PARSER_FEATURE;
    private Feature[] features;

    private SerializeConfig serializeConfig;
    private SerializerFeature[] serializerFeatures = {SerializerFeature.WriteNullListAsEmpty,
            SerializerFeature.SkipTransientField,
            SerializerFeature.DisableCircularReferenceDetect};

    public static FastJsonConverterFactory create() {
        return new FastJsonConverterFactory();
    }

    private FastJsonConverterFactory() {
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        return new FastJsonResponseBodyConverter<>(type, mParserConfig, featureValues, features);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return new FastJsonRequestBodyConverter<>(serializeConfig, serializerFeatures);
    }

    //get,set方法
    ...
}

+FastJsonRequestBodyConverter类,对请求转化:

final class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
    private SerializeConfig serializeConfig;
    private SerializerFeature[] serializerFeatures;

    FastJsonRequestBodyConverter(SerializeConfig config, SerializerFeature... features) {
        serializeConfig = config;
        serializerFeatures = features;
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        byte[] content;
        if (serializeConfig != null) {
            if (serializerFeatures != null) {
                content = JSON.toJSONBytes(value, serializeConfig, serializerFeatures);
            } else {
                content = JSON.toJSONBytes(value, serializeConfig);
            }
        } else {
            if (serializerFeatures != null) {
                content = JSON.toJSONBytes(value, serializerFeatures);
            } else {
                content = JSON.toJSONBytes(value);
            }
        }
        return RequestBody.create(MEDIA_TYPE, content);
    }
}

+FastJsonResponseBodyConverter类,对响应转化:

final class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private static final Feature[] EMPTY_SERIALIZER_FEATURES = new Feature[0];

    private Type mType;

    private ParserConfig config;
    private int featureValues;
    private Feature[] features;

    FastJsonResponseBodyConverter(Type type, ParserConfig config, int featureValues,
                                  Feature... features) {
        mType = type;
        this.config = config;
        this.featureValues = featureValues;
        this.features = features;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T convert(ResponseBody value) throws IOException {
        try {
            if (mType == String.class) {
                return (T) value.string();
            }
            return JSON.parseObject(value.string(), mType, config, featureValues,
                    features != null ? features : EMPTY_SERIALIZER_FEATURES);

        } finally {
            value.close();
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,292评论 19 139
  • 本文将顺着构建请求对象->构建请求接口->发起同步/异步请求的流程,分析Retrofit是如何实现的。 开始之前,...
    zhuhf阅读 1,649评论 0 10
  • 什么是Retrofit2 Retrofit是一个给Android和Java用的类型安全的HTTP客户端,它将网络请...
    不羁的木木阅读 1,193评论 0 49
  • 一、什么是Retrofit A type-safe HTTP client for Android and Jav...
    andcoder阅读 797评论 2 3
  • 新的一年,听到的一句最深情的告白:在我最痛苦,迷茫,失落,低谷的时候,陪我从一个骄傲的男孩,变成一个知进退懂担当的...
    笑音无恙阅读 4,577评论 0 2