8

これを使用して、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,...

キューは常に存在し、構築もしていますが、q0が常に存在するとは限りません。では、どうすればq0の存在を確認できますか?そして、Gsonライブラリを使用してそれをチェックする方法はありますか?

前もって感謝します!

4

2 に答える 2

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;
}
于 2012-04-08T15:51:46.877 に答える
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でない場合。

于 2012-04-08T15:38:25.780 に答える