美文网首页
GsonConverterFactory

GsonConverterFactory

作者: 魔女小姐的猫 | 来源:发表于2020-07-24 07:39 被阅读0次

应用创景:

在使用Retrofit请求数据数时,有一个addConverterFactory() 转化器场,这里我们重写了GsonConverterFactory.create()的源码,扩展了GsonResponseBodyConverter的功能,判断响应回来的字符串.class

Retrofit retrofit = new Retrofit.Builder()
                            .addConverterFactory(MvpGsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .baseUrl(Commons.BASE_URL)
                            .client(okHttpClient)
                            .build();

MvpGsonConverterFactory

package com.example.demo1mvp.json;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
public class MvpGsonConverterFactory extends Converter.Factory {
   /**
    * Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
    * decoding from JSON (when no charset is specified by a header) will use UTF-8.
    */
   public static MvpGsonConverterFactory create() {
       return create(new Gson());
   }

   /**
    * Create an instance using {@code gson} for conversion. Encoding to JSON and
    * decoding from JSON (when no charset is specified by a header) will use UTF-8.
    */
   @SuppressWarnings("ConstantConditions") // Guarding public API nullability.
   public static MvpGsonConverterFactory create(Gson gson) {
       if (gson == null) throw new NullPointerException("gson == null");
       return new MvpGsonConverterFactory(gson);
   }

   private final Gson gson;

   private MvpGsonConverterFactory(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 MvpGsonResponseBodyConverter<>(gson, adapter,type);
   }

   @Override
   public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                         Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
       TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
       return new MvpGsonRequestBodyConverter(gson, adapter);
   }
}

MvpGsonRequestBodyConverter<T>

package com.example.demo1mvp.json;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class MvpGsonRequestBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    MvpGsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override public T convert(ResponseBody value) throws IOException {
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try {
            T result = adapter.read(jsonReader);
            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
            return result;
        } finally {
            value.close();
        }
    }
}

MvpGsonResponseBodyConverter<T>

package com.example.demo1mvp.json;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;

public class MvpGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    //增加了type类型
    private Type type;

    MvpGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter,Type type) {
        this.gson = gson;
        this.adapter = adapter;
        this.type = type;
    }

    @Override public T convert(ResponseBody value) throws IOException {
        if (type == String.class) {
            try {
                MediaType mediaType = value.contentType();
                Charset charset = null;
                if (mediaType == null) {
                    charset = mediaType.charset();
                }
                String s = new String(value.bytes(), charset == null ? StandardCharsets.UTF_8 : charset);
                return (T) s;
            } finally {
                value.close();
            }
        } else {
            JsonReader jsonReader = gson.newJsonReader(value.charStream());
            try {
                T result = adapter.read(jsonReader);
                if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                    throw new JsonIOException("JSON document was not fully consumed.");
                }
                return result;
            } finally {
                value.close();
            }
        }
    }
}

详细介绍Retrofit2之GsonConverter

相关文章

网友评论

      本文标题:GsonConverterFactory

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