在Java中将HashMap格式化为JSON

时间:2019-07-18 20:05:31

标签: java json serialization hashmap

假设我有以下HashMap需要转换为JSON:

HashMap <String, String> test1 = {k1,v1},{k2,v2},{k3,v3},{k4,v4};

我知道使用JSONObject创建JSON输出:

JSONObject json = new JSONObject ( test1 );

但是,json将采用以下格式: {"k1":"v1","k2":"v2","k3":"v3","k4":"v4"}

我希望输出是这样的:

[{"key":"k1","value":"v1"},
{"key":"k2","value":"v2"},
{"key":"k3","value":"v3"},
{"key":"k4","value":"v4"}]

有人对如何转换为格式化的JSON有意见吗?进一步的问题:如果HashMap的键是Set of String怎么办?

HashMap <String, Set<String>> test1 = {k1,{v1,v2,v3}},{k2,{v4,v5,v6}},{k3,{v7,v8,v9}};

我希望输出是这样的:

[{"key":"k1","value":["v1","v2","v3"]},
{"key":"k2","value":["v4","v5","v6"]},
{"key":"k3","value":["v7","v8","v9"]}]

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

假设您正在使用json-简单库,则可以先将每个映射条目转换为新的JSONObject,然后将它们全部添加到JSONArray中:

Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3", "k4", "v4");
JSONArray arr = map.entrySet().stream()
    .map(e -> Map.of("key", e.getKey(), "value", e.getValue()))
    .map(JSONObject::new)
    .collect(JSONArray::new, JSONArray::add, JSONArray::addAll);
System.out.println(arr); 

将打印:

[{"value":"v4","key":"k4"},{"value":"v3","key":"k3"},{"value":"v2","key":"k2"},{"value":"v1","key":"k1"}]

输出JSONArray中元素的顺序将取决于所使用的映射,如果要在迭代时保留插入顺序,则需要LinkedHashMap。否则,您必须使用比较器对流进行排序。