如何处理此问题,以便它不会出现以下错误
JSONObject dataObject = new JSONObject(data);
String currentDynamicKey = "7";
JSONObject currentDynamicValue = dataObject.getJSONObject(currentDynamicKey);
错误:
org.json.JSONException: Value at 7 of type java.lang.String cannot be converted to JSONObject
json数据:
{"2":{"id":2,"title":"Battleship game","enabled":"1","connection_alert":"1","prot":"2","port":"6410","analysis":"1","send_data":"Analysis Data box","regex":"\/HTTP\/1.1 404 Not Found\/","send_on":false,"analysis_alert_title":"404","analysis_alert_body":"not found","analysis_alert_body_false":"found"},"7":""}
你可以看到最后7在空。我该怎么做才能检查它是否为空?
答案 0 :(得分:2)
只需使用optJSONObject(String name)
代替getJSONObject(String name)
:
返回按名称映射的值(如果存在)并且是JSONObject。否则返回null。
然后检查返回值。