Help parsing Yahoo search results with JSON Not a JsonArray exception
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 re开发者_如何学JAVAceived, 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:
JSONArray getArrayOrObject(JSONObject parent, String name) {
JSONArray results = parent.optJSONArray(name);
if (results == null) {
results = new JSONArray();
JSONObject object = parent.optJSONObject("Result");
if (object != null) {
results.put(object);
}
}
return results;
}
You want to check if totalResultsReturned == 1. if it is, you should use .getJSONObject('Result') instead, and then construct a JSONArray with that object as the first value (http://www.json.org/javadoc/org/json/JSONArray.html).
Presumably you're handling the case where there are 0 results as well.
精彩评论