gpt4 book ai didi

java - 将映射值添加到具有相同关键字段名称的 JSON 对象

转载 作者:行者123 更新时间:2023-12-01 19:57:49 25 4
gpt4 key购买 nike

我有以下 Java map 。 Map<String, String>包含以下值:

876234876, google
mike@hotmail, hotmail
9879892, google

我需要将其转换为以下 JSON 对象结构,而 Java JSON 对象不是我的 friend 。

"addresses" : [
{ "address":"876234876", "domain":"google" },
{ "address":"mike@hotmail", "domain":"hotmail" },
{ "address":"9879892", "domain":"google" }
]

最佳答案

要创建您要求的 JSON,您需要插入 JSONObject进入JSONArray 。所以对于每个 Entry您的Map<String, String> ,创建一个JSONObject喜欢 {"address": entry.key, "domain": entry.value}并将它们添加到 JSONArray .

让我们使用Stream.map创建该对象并将结果直接插入数组:

public static JSONObject createJson(Map<String, String> value) {
JSONObject result = new JSONObject();
JSONArray addresses = new JSONArray();
result.put("addresses", addresses);

value.entrySet().stream() //iterate the map
.map(e -> { //build an object
JSONObject address = new JSONObject();
address.put("address", e.getKey());
address.put("domain", e.getValue());
return address;
})
.forEach(addresses::put); //insert into the array

return result;
}

并使用以下命令进行测试:

public static void main(String[] args) {
Map<String, String> values = new HashMap<>();
values.put("876234876", "google");
values.put("mike@hotmail", "hotmail");
values.put("9879892", "google");
System.out.println(createJson(values).toString(4));
}

结果:

{"addresses": [
{
"address": "9879892",
"domain": "google"
},
{
"address": "876234876",
"domain": "google"
},
{
"address": "mike@hotmail",
"domain": "hotmail"
}
]}

使用API​​:JSON In Java

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>

关于java - 将映射值添加到具有相同关键字段名称的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48907828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com