我正在开发与响应为 JSON 的 Rest 服务的集成。
我做的第一个请求是登录,它有两个可能的返回。
通常积极的登录响应如下所示:
{"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":","}}}
假设它永远不会改变格式,我可以使用 GSON 反序列化它。但是,如果 JSON 响应以不同的方式出现怎么办?就像我尝试使用错误的用户名/密码登录一样?
否定的反应是这样的:
{"error":{"class":"com.attask.biz.externallogin.ExternalLoginException","message":"The following error occurred while authenticating with an external system: Invalid password"}}
所以我的问题是,有没有办法让 GSON 选择最适合反序列化的对象,或者我是否必须尝试反序列化,假设它已经正确并在 catch 块上处理它?
我希望我能说清楚,我期待着建议。
干杯
保罗·阿尔梅达