英文:
Get Value in Array Value in HashMap
问题
"results":
[
{
"name": "xxx",
"Data": {
"id": 23
}
}
]
我有一个返回的 JSON 数据,格式如上所示,我使用 HashMap 进行解析,但无法访问 Data 数组。如何获取 Data 数组中的 id 值?
List<HashMap<String, Object>> personList = getCurrentResponse().jsonPath().getList("results");
for (HashMap<String, Object> person : personList) {
if (person.get("name").equals(name)) {
int id = (int) ((HashMap<String, Object>) person.get("Data")).get("id");
return id;
}
}
在上述代码示例中,我收到了 Null 异常。
英文:
"results":
[
{
"name": "xxx",
"Data": {
"id": 23
}
}
]
I have a json returning like this and I meet it with HashMap, but I can access the Data array. How can I get the id in the data array?
List<HashMap<String, Object>> personList = getCurrentResponse().jsonPath().getList("results");
for (HashMap<String, Object> person : personList ) {
if (person .get("name").equals(name)) {
int id= (int) (person .get("Data.id"));
return id;
I am getting NullException from the code sample above
答案1
得分: 1
你应该首先将数据作为HashMap获取,然后从中获取id:
HashMap<String, Object> data = (HashMap<String, Object>) person.get("Data");
int id = (int) data.get("id");
英文:
You should first get Data as a HashMap, and then get id from it:
HashMap<String, Object> data = (HashMap<String, Object>) person .get("Data");
int id= (int) (data.get("id"));
答案2
得分: 0
你只能每次获取一级,你可以调用 .get()
两次
for (HashMap<String, Object> person : personList) {
if (person.get("name").equals(name)) {
return person.get("Data").get("id");
}
}
英文:
You can retrieve only one level at a time, you may call .get()
twice
for (HashMap<String, Object> person : personList ) {
if (person .get("name").equals(name)) {
return person.get("Data").get("id");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论