如何将 JSON 数组转换为 Java 中的哈希映射?

huangapple 未分类评论49阅读模式
英文:

How to convert json arrays to hashmap in java?

问题

Map<String, Object> map = new HashMap<String, Object>();
JSONArray jsonArray = new JSONArray();
// 假设有两个人
for (Person person : persons) {
    Map<String, Object> mapPerson = new HashMap<String, Object>();
    mapPerson.put("name", "name");
    mapPerson.put("age", "age");
    jsonArray.put("", mapPerson);
}
map.put("", jsonArray);

我希望对象 map 的值为:

[
{
"name": "name",
"age": "age"
},
{
"name": "name",
"age": "age"
}
]

但实际上是:

{=
[
{
"name": "name",
"age": "age"
},
{
"name": "name",
"age": "age"
}
]
}

我该如何实现上述要求?谢谢

英文:

Edited for clarification, I have below code:

Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
JSONArray jsonArray = new JSONArray();
// Assume there are 2 persons
for(Person person: persons) {
Map&lt;String, Object&gt; mapPerson = new HashMap&lt;String, Object&gt;();
mapPerson.put(&quot;name&quot;, &quot;name&quot;);
mapPerson.put(&quot;age&quot;, &quot;age&quot;);
jsonArray.put(&quot;&quot;, mapPerson);
}
map.put(&quot;&quot;, jsonArray);

I want the value of object map to be:

[
{
&quot;name&quot;:&quot;name&quot;,
&quot;age&quot;:&quot;age&quot;
},
{
&quot;name&quot;:&quot;name&quot;,
&quot;age&quot;:&quot;age&quot;
}
]

but it is:

{=
[
{
&quot;name&quot;:&quot;name&quot;,
&quot;age&quot;:&quot;age&quot;
},
{
&quot;name&quot;:&quot;name&quot;,
&quot;age&quot;:&quot;age&quot;
}
]
}

How can I achieve the above? Thanks

huangapple
  • 本文由 发表于 2020年4月6日 19:35:29
  • 转载请务必保留本文链接:https://java.coder-hub.com/61058853.html
匿名

发表评论

匿名网友

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

确定