简体   繁体   English

当响应未如预期时,如何使用GSON解析json?

[英]How to parse a json with GSON when the response doesn't come as expected?

I'm developing a integration with a Rest service which the response is a JSON. 我正在开发与Rest服务的集成,该服务的响应是JSON。

The first request I do is to login which has two possible returns. 我要做的第一个请求是登录,它有两个可能的返回值。

Usually the positive login response comes like below: 通常,肯定的登录响应如下所示:

    {"data":{"userID":"4f561b74001ff932afd58200a752b821","sessionID":"6cc960751eef45db83dd8db7f47337a6","versionInformation":{"currentAPI":"v2.0","buildNumber":"28b12d751c5ea88d393e68285ac57ed309ae04fa","apiVersions":{"v1.0":"\/attask\/api\/v1.0\/","v2.0":"\/attask\/api\/v2.0\/"},"lastUpdated":"2013\/02\/12 17:42:57","release":"R16","version":"4.0"},"locale":"pt_BR","timeZone":"America\/Sao_Paulo","timeZoneName":"Brasilia Time","iso3Country":"BRA","iso3Language":"por","currency":{"useNegativeSign":true,"fractionDigits":2,"symbol":"R$","ID":"BRL","groupingSeparator":".","decimalSeparator":","}}}

I've no problem to deserialize this using GSON assuming it'll never change the format. 假设它永远不会更改格式,那么使用GSON反序列化这没有问题。 But what if when the JSON response comes in a different way? 但是,如果JSON响应以其他方式出现时该怎么办? Like I tried to login with a wrong username/password ? 就像我尝试使用错误的用户名/密码登录吗?

The negative response would be something like this: 否定的响应将是这样的:

    {"error":{"class":"com.attask.biz.externallogin.ExternalLoginException","message":"The following error occurred while authenticating with an external system: Invalid password"}}

So my question is, is there a way to make GSON pick which is the most appropriate object to deserialize or do I have to try to deserialize assuming it has come right and handle it on a catch block ? 所以我的问题是,有没有办法使GSON选择最适合反序列化的对象,或者我必须尝试反序列化以使其正确并在catch块上进行处理?

I hope I could make it clear and I'm looking forward for suggestions. 希望我能说清楚一点,并期待提出建议。

Cheers 干杯

Paulo Almeida 保罗·阿尔梅达

Assuming a proper REST service the response code should indicate wether the request was successful or not. 假设正确的REST服务,响应代码应指示请求是否成功。 In cases like that you can make your decision based off the differing response codes. 在这种情况下,您可以根据不同的响应代码做出决定。

For improperly implemented REST services, you might want to deserialize the response data into a 'weak' (map) type, like JsonObject (which you can process further if need be, depending on the contents of the processed data). 对于未正确实现的REST服务,您可能需要将响应数据反序列化为“弱”(映射)类型,例如JsonObject(根据需要,可以进一步处理,具体取决于处理数据的内容)。

What I do is use com.google.gson.JsonParser instead of trying to deserialize to an object. 我要做的是使用com.google.gson.JsonParser而不是尝试反序列化为对象。 Withthat interface you can examine the top level element (perhaps checking for a specific attribute) and then decide what to do. 使用该界面,您可以检查顶层元素(也许检查特定属性),然后决定要做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM