Rest 如何使用Json作为数组创建哈希映射
就像下面的Json一样,我想创建一个HashMap-Rest 如何使用Json作为数组创建哈希映射,rest,api,automation,hashmap,rest-assured,Rest,Api,Automation,Hashmap,Rest Assured,就像下面的Json一样,我想创建一个HashMap- { "name": "John", "lname": "Smith", "age": "25", "address": { "streetAddress": "21 2nd Street", "city": "New York" }, "phoneNumbers": [ { "type": "home",
{
"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");
HashMap jsonAsMap=newhashmap();
jsonAsMap.put(“名称”、“拉杰什”);
jsonAsMap.put(“lname”、“Singh”);
jsonAsMap.put(“年龄”、“45”);
HashMap=newHashMap();
地图放置(“街道地址”、“123民事线路”);
地图放置(“城市”、“德里”);
jsonAsMap.put(“地址”、“地图”);
这个想法是创建一个HashMap,其中数组作为列表
Arrays.asList(new HashMap<String, Object>()
Arrays.asList(新的HashMap()
完整代码如下:
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)
Map Map=newhashmap();
地图。放置(“姓名”、“约翰”);
地图放置(“lname”、“Smith”);
地图放置(“年龄”,“25”);
HashMap地址=新的HashMap();
地址。put(“街道地址”、“123民事线路”);
地址:put(“城市”、“德里”);
地图放置(“地址”,地址);
put(“phoneNumbers”、Arrays.asList(newhashmap()){
{
put(“type”、“home”);
放置(“编号”,“212 555-1234”);
}},新的HashMap(){{
输入(“打字”、“传真”);
放入(“编号”,“646555-4567”);
}}
));
字符串json=new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(映射);
System.out.println(json)
这将以json生成输出,但与您发布的json的顺序不同,如果您需要相同的顺序,请使用
LinkedHashMap
我建议您使用JSONObject
而不是HashMap,我已经回答了您的问题谢谢@WilfredClement。我们可以结束这个问题。