ratrofit +okhttp + gson 解析数据为空 (接口已返回json数据)
Posted 我叫白小飞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ratrofit +okhttp + gson 解析数据为空 (接口已返回json数据)相关的知识,希望对你有一定的参考价值。
这真是个无语的问题,我先是以为接口数据格式变了,但是我检查了json,发现没有问题,有把所有的字段对了一遍,命名也没有问题,然后就开始打断点,把request和response都打印了一遍,发现response里的解析的body确实是空的,然后就去找解析的位置,因为使用了ratrofit + okhttp + gson的框架结构,于是在okhttpCall的enqueue方法中,
public void enqueue(final Callback<T> callback)
Utils.checkNotNull(callback, "callback == null");
okhttp3.Call call;
Throwable failure;
synchronized(this)
if (this.executed)
throw new IllegalStateException("Already executed.");
this.executed = true;
call = this.rawCall;
failure = this.creationFailure;
if (call == null && failure == null)
try
call = this.rawCall = this.createRawCall();
catch (Throwable var7)
failure = this.creationFailure = var7;
if (failure != null)
callback.onFailure(this, failure);
else
if (this.canceled)
call.cancel();
call.enqueue(new okhttp3.Callback()
public void onResponse(okhttp3.Call call, Response rawResponse) throws IOException
retrofit2.Response response;
try
response = OkHttpCall.this.parseResponse(rawResponse);
catch (Throwable var5)
this.callFailure(var5);
return;
this.callSuccess(response);
public void onFailure(okhttp3.Call call, IOException e)
try
callback.onFailure(OkHttpCall.this, e);
catch (Throwable var4)
var4.printStackTrace();
private void callFailure(Throwable e)
try
callback.onFailure(OkHttpCall.this, e);
catch (Throwable var3)
var3.printStackTrace();
private void callSuccess(retrofit2.Response<T> response)
try
callback.onResponse(OkHttpCall.this, response);
catch (Throwable var3)
var3.printStackTrace();
);
注意到这个方法:OkHttpCall.this.parseResponse
retrofit2.Response<T> parseResponse(Response rawResponse) throws IOException
ResponseBody rawBody = rawResponse.body();
rawResponse = rawResponse.newBuilder().body(new OkHttpCall.NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build();
int code = rawResponse.code();
if (code >= 200 && code < 300)
if (code != 204 && code != 205)
OkHttpCall.ExceptionCatchingRequestBody catchingBody = new OkHttpCall.ExceptionCatchingRequestBody(rawBody);
try
T body = this.serviceMethod.toResponse(catchingBody);
return retrofit2.Response.success(body, rawResponse);
catch (RuntimeException var9)
catchingBody.throwIfCaught();
throw var9;
else
rawBody.close();
return retrofit2.Response.success((Object)null, rawResponse);
else
retrofit2.Response var5;
try
ResponseBody bufferedBody = Utils.buffer(rawBody);
var5 = retrofit2.Response.error(bufferedBody, rawResponse);
finally
rawBody.close();
return var5;
T body = this.serviceMethod.toResponse(catchingBody);这个方法返回了解析出来的数据,继续跟:
R toResponse(ResponseBody body) throws IOException
return this.responseConverter.convert(body);
它的实现是通过gson来做的,这个就不细看了,主要看一下返回值,直接是空的,然后,然后提示一个错误,某个字段解析出错,但是这里边直接catch 了,我又检查了该字段,发现是字段类型定义有问题,本来是个long类型的,可是接口返回的是个string类型的,解析异常。
以上是关于ratrofit +okhttp + gson 解析数据为空 (接口已返回json数据)的主要内容,如果未能解决你的问题,请参考以下文章