java - Java:来自 JSON 的数组数组
问题描述
我有一个 JSON Arrays of Array 像这样
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
我想检索“ html”的“ https://bbb.com ”和“ https://bcc.com ”,但我不知道该怎么做。
基于善意的评论,我提出以下内容。不知何故,“getJSONObject()”不能放。错误消息显示“无法解析 'JSONArray' 中的方法 'getJSONObject'”。
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
但是当我尝试使用以下内容时,不仅会检索“html”,还会检索“self”和其他信息。
String photoUrl = job.get("links").toString();
请告诉我如何只检索“html”。
我正在使用 IntelliJ。
解决方案
要遵循的步骤(假设您提到了正确的 JSONArray):
- 通过索引从您的 JSONArray 中获取 JSONObject,即。对于你的情况,
index=0
在这里 - 通过 key 获取内部 JSONObject
links
- 现在,通过以下键访问您的内容
html
您的案例示例:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
最好按照 Harshal 的建议继续检查密钥是否存在
推荐阅读
- python - 试图缩短我的 python 代码。有人有想法吗?
- vba - VBA Pivot 过滤器在每个过滤器项上重新计算表 - 如何避免这种情况?
- mysql - 如何获得取决于数据馈送的不同值的特定值?
- ios - 如何从 UITableViewCell 中加载 UITableView?
- ruby-on-rails - 将 ActiveStorage 资产从一个 S3 存储桶迁移到另一个
- ios - UIActivityViewController 将图像保存到照片库,但使用 false 调用其完成处理程序
- r - 累计值 CI
- android - 如何在 jetpack compose 中传递来自 Firestore 的查询的参数
- python - VSCode for Python 中未解决的导入
- powerbi-embedded - PowerBi EmbedToken 与任何工作区上的报告标识一起使用