如何创建带有数组的Json的哈希映射

问题描述 投票:0回答:1

就像在Json下面一样,我想创建一个HashMap-

{
    "name": "John",
    "lname": "Smith",
    "age": "25",
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York"

    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567" 
        }
    ] 
}

我已经尝试过下面的代码,但是我不确定如何添加“ PhoneNumber”,因为其中包含了数组。请帮助我-

HashMap<String,Object> jsonAsMap=new HashMap<String,Object>();
jsonAsMap.put("name", "Rajesh");
jsonAsMap.put("lname", "Singh");
jsonAsMap.put("age", "45");

HashMap<String,Object> map=new HashMap<String,Object>();

map.put("streetAddress", "123 Civil lines");
map.put("city", "Delhi");
jsonAsMap.put("address", "map");
rest api automation hashmap rest-assured
1个回答
1
投票

这个想法是创建一个以数组作为列表的HashMap,

Arrays.asList(new HashMap<String, Object>()

下面的完整代码:

    Map<String, Object> map = new HashMap<>();
    map.put("name", "John");
    map.put("lname", "Smith");
    map.put("age", "25");

    HashMap<String,Object> address=new HashMap<>();

    address.put("streetAddress", "123 Civil lines");
    address.put("city", "Delhi");
    map.put("address", address);

    map.put("phoneNumbers", Arrays.asList(new HashMap<String, Object>() {
        {
            put("type", "home");
            put("number", "212 555-1234");
        }},new HashMap<String, Object>() {{
            put("type", "fax");
            put("number", "646 555-4567");
        }}
        ));

    String json = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(map);

    System.out.println(json)

[这将在json中生成输出,但输出顺序与您发布的json的顺序不同,如果需要相同的顺序,请使用LinkedHashMap

© www.soinside.com 2019 - 2024. All rights reserved.