android判断是否json格式,android – 检查JSON中是否存在subObject

您可以尝试一下,如果尝试失败,则返回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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值