2014-03-01 42 views
0

如何处理这一点,以便它不会提供以下错误如何知道JSON字符串是否可以无错转换为JSONObject?

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

你正在使用哪个json解析器?有几十个,它们都有一个JSONObject或JsonObject类。 –

+0

这是一个Android应用程序 – Waqleh

回答

2

只需使用optJSONObject(String name)代替getJSONObject(String name)

如果存在的话,是一个JSONObject返回名称映射的值。否则返回null。

然后检查返回的值。

相关问题