gpt4 book ai didi

java - 访问嵌套在两个 JSON 数组内的 JSON 对象

转载 作者:行者123 更新时间:2023-12-01 16:53:30 25 4
gpt4 key购买 nike

我正在尝试创建一个日历。我有一个基本的“年”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

任何帮助表示赞赏。

最佳答案

正如评论中提到的,使用此代码进行转换:

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

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

关于java - 访问嵌套在两个 JSON 数组内的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61636907/

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