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

 
  
 
  
 
  
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer() {
    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;
}

你可能感兴趣的:(Android开发)