Convert the data of type Map to JSON String
suggest changeCode
Group group = new Group();
group.setId(1);
group.setName("Ke");
User user1 = new User();
user1.setId(2);
user1.setName("Liu");
User user2 = new User();
user2.setId(3);
user2.setName("Yue");
group.getList().add(user1);
group.getList().add(user2);
Map<Integer, Object> map = new HashMap<Integer,Object>();
map.put(1, "No.1");
map.put(2, "No.2");
map.put(3, group.getList());
String jsonString = JSON.toJSONString(map);
System.out.println(jsonString);
JSON here is Fastjson (com.alibaba.fastjson.JSON). Group and User are model classes with id, name, and, on Group, a list. Fastjson quotes map keys. The object below is what toJSONString prints. Keys left as bare numbers are not JSON.
{"1":"No.1","2":"No.2","3":[{"id":2,"name":"Liu"},{"id":3,"name":"Yue"}]}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents