Weird behavior when calling org.json.JSONObject.getJSONArray
Hey, I noticed this really weird behavior wh开发者_如何学Goen calling getJSONArray. This is my code:
JSONObject jsonObject = new JSONObject(data);
if (!jsonObject.getJSONObject("transfer").has("skill"))
return Collections.emptyList();
JSONArray events = jsonObject.getJSONObject("transfer").getJSONArray("skill");
now, whenever transfer has more than 1 skill elements, everything works great, but when there is only 1 skill element, Im getting an exception:
Caused by: org.json.JSONException: Value {"id":"2","name":"DOGS"} at skill of type org.json.JSONObject cannot be converted to JSONArray at org.json.JSON.typeMismatch(JSON.java:96) at org.json.JSONObject.getJSONArray(JSONObject.java:548) ....
Is that makes sense? Do I really have to catch the exception and handle this kind of array specific?
Thanks, Udi
Any time you retrieve a JSON Object surround your code with a try/catch block. This way your program will continue running when you get any unexpected JSON objects.
As for you error it looks like your JSONArray "skill" is not being stored as an array when there is only one item. If you are using a web service to create the JSON object the problem may lie in the web service.
In the JSON you are reading, when there is one element, it probably has something like:
skill: {"id":"2","name":"DOGS"}
rather than:
skill: [{"id":"2","name":"DOGS"}]
Note the difference between a single object and an array that contains a single object. In your code, you are using getJSONArray to ask for an array, resulting in an exception when it's not an array.
You would need to either check that the value of "skill" is an array before using getJSONArray, or assume it is an array and catch the exception to handle the single object case. Alternately, if you can modify the application that is generating the JSON, you could fix it to put the "skill" object inside an array even when there is just one.
精彩评论