将Map Value添加到相同键字段名称中的JSON对象

时间:2018-02-21 14:00:53

标签: java json

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

876234876, google
mike@hotmail, hotmail
9879892, google

我需要将它转换为以下JSON对象结构,Java JSON对象不是我的朋友。

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

3 个答案:

答案 0 :(得分:2)

要创建您要求的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>

答案 1 :(得分:1)

检查此解决方案:

List<String> addresses = new ArrayList<>();
        map.forEach((k, v) -> {
            Map<String, String> nn = new HashMap<>();
            nn.put("address", k);
            nn.put("domain", v);
            addresses.add(JSONValue.toJSONString(nn));
        });
        JSONObject result = new JSONObject(Collections.singletonMap("addresses", new JSONArray(addresses)));

答案 2 :(得分:0)

您的JAVA对象应如下所示:

地址列表

@XmlRootElement
public class Foo {

  private List<Address> addresses;

  // Getter, Setter, ...

}

<强>地址

public class Address {

  private String address;

  private String domain;

  // Getters, setters, ...

}