I’ve read so many posts and still can’t find or understand how to handle a result set that can have either 1 result, or an array of results. (From yahoo Search)
I can parse the results perfectly fine IF multiple results were received, but when there is only 1 search result I get the JSONException: blahblahbalh is not a JSONArray.
JSONArray results = resultObject.getJSONArray("Result");
Works fine when there are multiple results, but how can I FORCE the built-in JSON parser to accept it as a result when there is only 1 result returned from the Yahoo Query?
This single result fails to parse to JSON Array:
{
"ResultSet": {
"totalResultsAvailable": "108",
"totalResultsReturned": "1",
"firstResultPosition": "1",
"ResultSetMapUrl": "http:\/\/maps.yahoo.com\/broadband\/?q1=Virginia+Beach%2C+VA+23454-4608tt=mexicantp=1",
"Result": {
"id": "12811175",
}
}
}
But this parses to JSONArray just fine:
{
"ResultSet": {
"totalResultsAvailable": "108",
"totalResultsReturned": "2",
"firstResultPosition": "1",
"ResultSetMapUrl": "http:\/\/maps.yahoo.com\/broadband\/?q1=Virginia+Beach%2C+VA+23454-4608tt=mexicantp=1",
"Result": [
{
"id": "12811175",
},
{
"id": "12814560",
}
]
}
}
Sorry if I’m babbling, but it’s driving me crazy that I just can’t figure out how to get a JSONArray with length of 1, out of the first result example.
Thanks much!
This is one of the problems with working with JSOn. If there are two objects than it is considered an JSONArray, otherwise it is considered a JSONObject.
As far as I know, you need to just assume that it could be either and code accordingly. You could wrap the messy details in a helper function like: