首页 > 解决方案 > 访问嵌套在两个 JSONArrays 中的 JSONObject

问题描述

我正在尝试创建一个日历。我有一个基本的“年”JSONArray,其中包含十二个“月”JSONArray,每个 JSONArray 都包含相应数量的“日”JSONObject。我使用以下代码制作了这个:

    int[] months = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    //base json containing all 12 months and 365 days
    JSONArray calendar = new JSONArray();
    for (int i = 0; i < 12; i++) {
        calendar.put(new JSONArray());
    }
    //insert jsonobject into each month for corresponding amount of days
    for (int i = 0; i < calendar.length(); i++) {
        for (int y = 0; y < months[i]; y++) {
            ((JSONArray) calendar.get(i)).put(new JSONObject());
        }
    }

但是,当尝试使用此代码访问某一天 JSONObject 时:

    System.out.println(calendar.get(month).get(day);

我收到此错误:

    The method get(int) is undefined for the type Object

任何帮助表示赞赏。

标签: javajson

解决方案


如评论中所述,使用此代码进行投射:

    System.out.println(((JSONArray)calendar.get(month)).get(day);

作品。但是,您也可以相应地使用 getJSONArray() 和 getJSONObject() 函数来解决此问题。


推荐阅读