java - 遍历 JSON 中收到的对象列表
问题描述
我有以下 JSON 数据:
[
{
"id": 4,
"siteName": "site1",
"addressLine1": "address1",
"addressLine2": "address2",
"town": "town1",
"postcode": "postcode1",
"contactName": "name1",
"contactNumber": "number1",
"contactEmail": "email1"
},
{
"id": 5,
"siteName": "site2",
"addressLine1": "address1",
"addressLine2": "address2",
"town": "town1",
"postcode": "postcode1",
"contactName": "name1",
"contactNumber": "number1",
"contactEmail": "email1"
},
]
我正在解析数据,但它只是输出一个长字符串。我想访问每个对象中的每个元素。
更新:我正在输出单个元素,但由于某种原因,“id”属性被认为是双精度的?
Map<String,Object> jsonArr = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
java.util.List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)jsonArr.get("root");
for(Map<String, Object> obj : content) {
Log.p((int)obj.get("id"));
Log.p((String)obj.get("siteName"));
Log.p((String)obj.get("addressLine1"));
Log.p((String)obj.get("addressLine2"));
Log.p((String)obj.get("town"));
Log.p((String)obj.get("postcode"));
Log.p((String)obj.get("contactName"));
Log.p((String)obj.get("contactNumber"));
Log.p((String)obj.get("contactEmail"));
}
解决方案
当您使用 Codename One 时,parseJSON
始终返回 a Map<String, Object>
,但当根元素是数组时表现不同。在这种情况下,返回Map
的对象包含一个对象,其键是"root"
您然后可以迭代以获取实际对象。
Map<String, Object> data = json.parseJSON(new InputStreamReader(
new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)data.get("root");
for(Map<String, Object> obj : content) {
Log.p(obj.getValue().toString());
}
有关详细信息,请参阅该方法的文档parseJSON
。
推荐阅读
- kubernetes - 我如何删除 DockerFile 并仅将 ci 文件与 kubernetes runner 一起使用
- c - getchar/putchar 在打印输入的字符时返回带有问号的框
- node.js - 带有额外文本输入字段的节点 js Multer 文件上传
- html - 将div放在表单标签中时如何仅获得一个滚动条
- javascript - 创建高度动态的输入表单组件
- url-redirection - 当 nutch 抓取重定向 URL 时,SOLR 中归档的 ID 与 URL 不同
- javascript - JS 脚本适用于 codepen 但不适用于 WordPress
- clojure - 为什么记录不是函数?
- react-native - 将文件保存到 expo 文件系统时出现问题。我得到了录制的 uri,但离开屏幕后似乎无法获取文件
- sql - 在sql server中使用左连接时如何对2条记录求和?