Retrofit2.0 GsonResponseBodyConverter类修改,解决网络访问默认返回空对象进入onFailure的问题

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/anskya520/article/details/52856428
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return new Date(json.getAsJsonPrimitive().getAsLong());
    }
});

//builder.registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory());
Gson gson = builder.create();
retrofit = new Retrofit.Builder()
        .baseUrl(Common.baseUrl)
        //.addConverterFactory(ScalarsConverterFactory.create())
        //.addConverterFactory(new StringConverterFactory())
        //.addConverterFactory(new JsonConverterFactory())
        .addConverterFactory(GsonConverterFactory.create(gson))
        //.addCallAdapterFactory()
        //.addConverterFactory(new FileRequestBodyConverterFactory())
        .client(okHttpClient)
        .build();

解决网络访问默认返回空对象进入onFailure的问题
修改了此处 GsonResponseBodyConverter ,

@Override
public T convert(ResponseBody value) throws IOException {
    JsonReader jsonReader = gson.newJsonReader(value.charStream());
    try {
        return adapter.read(jsonReader);  //原支持库没有catch
    }  catch (Exception e) {   
        e.fillInStackTrace();
    } finally {
        value.close();
    }
    return null;
}
展开阅读全文

没有更多推荐了,返回首页