gpt4 book ai didi

android - 检查 JSON 中是否存在子对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:01:23 25 4
gpt4 key购买 nike

我正在使用以下方法检查 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");

当我尝试检查子对象是否存在时出现问题。例如:

...,"queue":{"building":{"q0":{"id":177779,...

Queue 一直存在,building 也一直存在,但 q0 并不总是存在。那么,如何检查 q0 是否存在?还有,有没有办法使用 Gson 库检查它?

提前致谢!

最佳答案

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

关于android - 检查 JSON 中是否存在子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10063866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com