美文网首页
Retrofit使用FastJson

Retrofit使用FastJson

作者: 我是腿哥 | 来源:发表于2017-07-04 17:14 被阅读0次

介绍

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();
        }
    }
}

相关文章

网友评论

      本文标题:Retrofit使用FastJson

      本文链接:https://www.haomeiwen.com/subject/cuexhxtx.html