检查是否在JSON存在的子对象 [英] Checking if exists subObject in JSON

查看:177
本文介绍了检查是否在JSON存在的子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查,如果在一个JSON字符串对象存在使用这样的:

I'm checking if an object in a JSON string exists using this:

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");

当我尝试检查一个子对象存在的问题出现。例如:

The problem appears when I attempt to check if a sub object exists. e.g:

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

队列总是存在和建筑也有,但 Q0 是不是永远存在的。所以,我怎么能检查 Q0 的存在?而且,有没有办法使用GSON库检查吗?

Queue always exists and building also, but q0 is not always there. So, how can I check the existence of q0? And, is there a way to check it using the Gson library?

感谢你在前进!

推荐答案

您可以简单地给它一个尝试,返回NULL,如果尝试失败。或者你可以把你的企图成一小块一小块来监控失败。

You can simply give it a try and return null if the try failed. Or you can break your attempt up into little pieces to monitor where it fails.

/**
 * 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;
    }    
}

您也可以一步一步走,如果你要打印日志,为每个级别;

You could also go step by step, if you want to print logs for each level;

/**
 * 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;
}

这篇关于检查是否在JSON存在的子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆