java - 访问嵌套在两个 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
任何帮助表示赞赏。
解决方案
如评论中所述,使用此代码进行投射:
System.out.println(((JSONArray)calendar.get(month)).get(day);
作品。但是,您也可以相应地使用 getJSONArray() 和 getJSONObject() 函数来解决此问题。
推荐阅读
- javascript - 在 Vue 上到达 div 时添加动画效果或类
- angular - 服务中的错误处理程序声明的基本 Angular 语法问题
- java - Android - 获取索引 #0 、 #1 、 #2 的数字
- c# - 我的对象在上一个点击位置移动
- sql - 查找仅在给定日期之前的记录 (SQL)
- azure - 使用 AKS 时如何修复“Kibana 服务器尚未准备好”错误
- java - 如何检查 index+1 是否没有债券?
- php - 存储网络摄像头图像
- azure - Azure Active Directory 域服务 DNS 转发
- dart - Flutter StreamSubscription cancel() 在无状态小部件中未取消