简体   繁体   中英

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.

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. But what if when the JSON response comes in a different way? 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 ?

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. 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).

What I do is use com.google.gson.JsonParser instead of trying to deserialize to an object. Withthat interface you can examine the top level element (perhaps checking for a specific attribute) and then decide what to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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