我正在使用以下方法检查JSON字符串中是否存在对象:
JSONObject json = null;
try {
json = new JSONObject(myJsonString);
} catch (JSONException e) { e.printStackTrace(); }
if(json.has("myObject")) System.out.println("EXISTS");
else System.out.println("DOESN'T EXIST");
当我尝试检查子对象是否存在时,会出现问题。 e.g:
...,"queue":{"building":{"q0":{"id":177779,...
队列始终存在且构建,但 q0 并非总是存在。那么,我该如何检查 q0 的存在?并且,有没有办法使用Gson库检查它?
提前谢谢!
答案 0 :(得分:11)
您可以尝试一下,如果尝试失败,则返回null。或者你可以将你的尝试分解成小块来监视失败的地方。
/**
* This method will return the JSONObject q0, if it exists
* If it doesn't exist it will return NULL
*
*/
private JSONObject getQZero(JSONObject json)
{
try
{
return json.getJSONObject("queue").getJSONObject("building").getJSONObject("q0");
}
catch (JSONException e)
{
// This could be triggered either because there is no q0
// or because the JSON structure is different from what was expected.
return null;
}
}
如果你想打印每个级别的日志,你也可以一步一步地去;
/**
* This method will show where your jsonparsing fails.
* It will throw a JSONOException if the json is way different from what
* was expected, and otherwise it will print a log of where the parsing
* failed.
*/
private JSONObject getQZero(JSONObject json) throws JSONException
{
// Stop if no queue
if (! myObject.has("queue")
{
Log.d(TAG, "no queue!");
return null;
}
JSONObject queue = myObject.getJSONObject("queue");
// Stop if no building
if (! queue.has("building")
{
Log.d(TAG, "no building!");
return null;
}
JSONObject building = queue.getJSONObject("building")
// Stop if no q0
if (! building.has("q0"))
{
Log.d(TAG, "no q0!");
return null;
}
JSONObject q0 = building.getJSONObject("q0");
// Q0 is returned here. If the method returned earlier, it returned NULL
// You could also do nested ifs, but the indentation gets crazy
return q0;
}
答案 1 :(得分:1)
使用例外情况
try {
JSONObject i = json. getJSONObject("q0");
// Is there do something
} catch (JSONException e) {
// Isn't there
}
http://www.json.org/javadoc/org/json/JSONObject.html#getJSONObject(java.lang.String)
JSONException - 如果找不到键或者值不是JSONObject。