java将Map或List<Map>转json字符串
解决方法:
首先maven引入fastjson jar依赖包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>
List<Map> listMap = new ArrayList<Map>();
Map map1 = new HashMap();
map1.put("小明","员工");
map1.put("小军","主管");
String jsonString1= JSON.toJSONString(map1);
System.out.println(jsonString1);
Map map2 = new HashMap();
map2.put("小王", "员工");
map2.put("小红", "主管");
listMap.add(map1);
listMap.add(map2);
String jsonString2= JSON.toJSONString(listMap);
System.out.println(jsonString2);
输出:
jsonString1转化后:{"小明":"员工","小军":"主管"}
jsonString2转化后:[{"小明":"员工","小军":"主管"},{"小王":"员工","小红":"主管"}]