在我的json响应中,我得到了json数组,其中还有80个其他json对象,每个对象中都有元素,有些对象也有json array。那么,如何检查json数组是否存在?
我也试过Optjsonarray,但它对我不起作用。
这是我的代码:

public static void insertMyDiaryValues(final JSONObject jobject)
        throws Throwable {
    String arrOfColumn[] = new String[] { "uuid", "date", "title", "diary",
            "pictureurl", "pictureWidth", "pictureHeight", "child" };
    try {

        SmartTable DiaryData = null;
        DiaryData = SmartApplication.REF_SMART_APPLICATION.getDataHelper()
                .getTableList().get(DBTblNames.MyDiaryValues);
        try {

            JSONArray jarr = new JSONArray(jobject.getJSONArray("diary"));

            for (int i = 0; i < jarr.length(); i++) {
                // String childValue = ""
                // + jarr.getJSONObject(i).getJSONArray("child").length();
                // System.out.println("child Value :-"
                // + jarr.getJSONObject(i).getJSONArray("child").length());

                // if (!(childValue == null)) {

                DiaryData.insertRow(
                        arrOfColumn,
                        new String[] {

                                jarr.getJSONObject(i).get("uuid")
                                        .toString(),
                                jarr.getJSONObject(i).get("date")
                                        .toString(),
                                jarr.getJSONObject(i).get("title")
                                        .toString(),
                                jarr.getJSONObject(i).get("diary")
                                        .toString(),
                                jarr.getJSONObject(i).get("pictureurl")
                                        .toString(),
                                jarr.getJSONObject(i).get("pictureWidth")
                                        .toString(),
                                jarr.getJSONObject(i).get("pictureHeight")
                                        .toString(),
                                ""
                                        + jarr.getJSONObject(i)
                                                .getJSONArray("child")
                                                .length()

                        });

            }

        } catch (Exception e) {

        }

    }

    catch (Exception e) {
        // TODO: handle exception
    }
}

最佳答案

只需使用try catch case进行检查:

try{
     JSONArray jsonArray = jsonObject.getJSONArray("key");
}catch (JSONException e){
     e.printStackTrace();
     // here write your code to get value from Json object which is not getJSONArray.
}

关于android - 检查json对象是否包含json数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27149239/

10-10 18:05
查看更多