获取HashMap中的数组值。

huangapple go评论67阅读模式
英文:

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 异常。

英文:
 &quot;results&quot;: 
[
        {
            &quot;name&quot;: &quot;xxx&quot;,
            &quot;Data&quot;: {
                &quot;id&quot;: 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&lt;HashMap&lt;String, Object&gt;&gt; personList = getCurrentResponse().jsonPath().getList(&quot;results&quot;);
   for (HashMap&lt;String, Object&gt; person : personList ) {
      if (person .get(&quot;name&quot;).equals(name)) {
          int id= (int) (person .get(&quot;Data.id&quot;));
          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&lt;String, Object&gt; data = (HashMap&lt;String, Object&gt;) person .get(&quot;Data&quot;);
int id= (int) (data.get(&quot;id&quot;));

答案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&lt;String, Object&gt; person : personList ) {
    if (person .get(&quot;name&quot;).equals(name)) {
        return person.get(&quot;Data&quot;).get(&quot;id&quot;);
    }
} 

huangapple
  • 本文由 发表于 2020年8月10日 21:32:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63341269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定