Reputation: 111
Like in below Json, i want create an 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"
}
]
}
I have tried below code, but i am not sure how to add "PhoneNumber" as it's having Array in it.Kindly help me-
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");
Upvotes: 0
Views: 245
Reputation: 2774
The idea is to create a HashMap with Arrays as list,
Arrays.asList(new HashMap<String, Object>()
Complete code below :
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)
This will generate the output in json but not in the same order as the json you have posted, if you need the same order then use LinkedHashMap
Upvotes: 1