Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[问答] 关于后台接口返回两种类型json串,retrofit解析失败问题。 #510

Open
Airsaid opened this issue Jul 27, 2016 · 10 comments

Comments

@Airsaid
Copy link

Airsaid commented Jul 27, 2016

一般后台接口定义的时候,都会返回:

{
    "status": 0,
    "msg": "验证码发送成功",
    "data": "932088"
}

其中status和msg是固定的,而data中的内容是变化的,当请求成功后,data中就有数据,而失败时,data中就没有数据,这时候,retrofit就会直接请求失败。 请问下该如何解决这种情况呢?

@lumenghz
Copy link

你有看错误信息吗?当为空的时候应该是这样的。

{
    "status": 0,
    "msg": "验证码发送成功",
    "data": ""
}

我自己在用的时候不会请求失败,你可以在okhttp打印一下请求结果。看一下具体错误,如果有logcat的信息就贴出来一下 💃

@Airsaid
Copy link
Author

Airsaid commented Jul 27, 2016

没错,当为空的时候,data中是空字符串,这时候retrofit就会直接走onFailure回调,是没有错误信息的。

@Airsaid
Copy link
Author

Airsaid commented Jul 27, 2016

其实当后台统一了data中的类型就不会有问题了,但是如果类型不一样。那么我就不知道该如何解决了。

@lumenghz
Copy link

我意思是即使那个data字段为空也不会onFailure,所以你还是先检查一下你的代码。

@Airsaid
Copy link
Author

Airsaid commented Jul 27, 2016

会的,我的代码没有任何关系,对了为空之前data中的数据是一个json对象。

@lumenghz
Copy link

data中是什么没关系,拿下来的反正都是字符串,空就是"data":""喽,不会走onFailure的,Gson转化成model之后你getData()的值为null,只会这样,不会到onFailure,我可以确定。

@Airsaid
Copy link
Author

Airsaid commented Jul 27, 2016

是吗? 那你的情况可能和我的不一样呢。我使用retrofit2进行网络请求的时候,操作成功时,由于data中返回的是jsonobject,那么就没有问题了,Gson正常解析。 当操作失败,data中后台给的是空字符串,这个时候Gson就会解析失败。导致retrofit2直接走onFailure回调。 我试图没让retrofit2直接解析,而是直接获取到json数据,然后再自己用Gson进行解析,发现依然是我上述说的这种情况。后来我让后台将data中的数据类型进行统一,解决了这个问题。 还是非常感谢你的帮助,Thx!

@kyosky110
Copy link

其实你这个问题可以用gson来解决,给gson注册个TypeAdapter对你返回结果进行过滤解析,如果返回成功,就解析data里面的数据,返回失败,就不解析data里面的数据。可以参考文章http://blog.csdn.net/kyosky110/article/details/51996199

@hss01248
Copy link

hss01248 commented Sep 26, 2016

gson的typetoken会出现泛型擦除的情况.最靠谱的还是optString后在判断.

String str = response.optString("data");
                if (TextUtils.isEmpty(str) || "[]".equals(str)
                        || "{}".equals(str)  || "null".equals(str)) {
                    myListener.onEmpty();

@aohanyao
Copy link

可以尝试自定义GsonResponseConverter,你这个情况和我的一模一样,后台返回的数据并不是规范的retrofitAPI。

http://www.jianshu.com/p/2263242fa02d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants