假设我有以下地图
Map<String, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("First in list");
list.add("Second in list");
map.put("First in map", list);
那么如何使用 javax.json 库直接将其转换为JSON字符串?
答案 0 :(得分:2)
我刚刚尝试了以下
Map<String, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("First in list");
list.add("Second in list");
List<String> list1 = new ArrayList<>();
list1.add("First in secondlist");
list1.add("Second in secondlist");
map.put("First in map", list);
map.put("Second in map", list1);
final JsonArrayBuilder outerJsonArray = Json.createArrayBuilder();
map.forEach((key, innerList) -> {
JsonArrayBuilder innerJsonArray = Json.createArrayBuilder();
innerList.forEach(item -> innerJsonArray.add(item));
outerJsonArray.add(Json.createObjectBuilder().add(key, innerJsonArray));
});
JsonArray usersJson = outerJsonArray.build();
System.out.println(usersJson.toString());
生成的JSON数组(缺少插入顺序)
[
{
"Second in map": [
"First in secondlist",
"Second in secondlist"
]
},
{
"First in map": [
"First in list",
"Second in list"
]
}
]