In my code I my a call to a service. from the returned json object I am interested in an object. this object is a json array. sometimes, depending on the provided info in the submit this json array object is empty or does not exist.
How can I check if the object in the json object is of type jsonarray before I create an object out from it?
JSONObject VODB = (JSONObject) JSONreturnObj.get("VODB");
if (null != VODB.get("KNDV430")){
if (VODB.getJSONArray("KNDV430") instanceof JSONArray){
JSONArray KNDV430 = VODB.getJSONArray("KNDV430");
customer.setCustResp((String) ((JSONObject)KNDV430.get(0)).get("responsible"));
}
}
now I get a message in my server log:
org.json.JSONException: JSONObject["KNDV430"] is not a JSONArray.
which I want to avoid.
How should I adapt my code?
Replace
if (VODB.getJSONArray("KNDV430") instanceof JSONArray)
with
if (VODB.get("KNDV430") instanceof JSONArray)
You're getting that error from the first getJSONArray in the condition of the if. So this should work:
JSONObject VODB = (JSONObject) JSONreturnObj.get("VODB");
if (null != VODB.get("KNDV430")){
if (VODB.get("KNDV430") instanceof JSONArray){
JSONArray KNDV430 = VODB.getJSONArray("KNDV430");
...
}
}
您可以查看方法JSONObject.getJSONArray()的源代码。
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.