如何使用 Json 作为数组创建哈希映射
How to create Hash Map with a Json which as an array in it
像下面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" 因为它在 it.Kindly 中有 Array 帮助我-
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,
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
像下面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" 因为它在 it.Kindly 中有 Array 帮助我-
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,
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