将Map <string,object =“”>的嵌套地图值“移动”到顶层

时间:2018-11-07 19:38:12

标签: java java-8

采用已转换为Map<String, Object>的JSON:

{
  "key1": "value1",
  "key2": {
    "nestedKey1": "nested value",
    "nestedKey2": {
      "nestedKey1": "nested value"
    }
  }
}

其中Object的值可以是某种原始类型,也可以是嵌套的Map<String, Object>。 我的目标是获取平面图

{
  "key1": "value1",
  "key2.nestedKey1": "nested value",
  "key2.nestedKey2.nestedKey1": "nested value"
}

如何?已经有图书馆了吗?

2 个答案:

答案 0 :(得分:3)

是的,您也可以在Java8中做到这一点。

主要测试方法:

private Map<String, Object> flatten(Map<String, Object> in) {
    return in.entrySet().stream()
        .flatMap(entry -> flatten(entry).entrySet().stream())
        .collect(Collectors.toMap( 
               Map.Entry::getKey, 
               Map.Entry::getValue));
}

private Map<String, Object> flatten(Map.Entry<String, Object> in) {
  // for other then Map objects return them
  if (!Map.class.isInstance(in.getValue())) {
    return Collections.singletonMap(in.getKey(), in.getValue());
  }
  // extract the key prefix for nested objects
  String prefix = in.getKey();
  Map<String, Object> values = (Map<String, Object>) in.getValue();
  // create a new Map, with prefix added to each key
  Map<String, Object> flattenMap = new HashMap<>();
  values.keySet().forEach(key -> {
    // use a dot as a joining char
    flattenMap.put(prefix + "." + key, values.get(key));
  });
  // use recursion to flatten the structure deeper
  return flatten(flattenMap);
}

Transformer方法:

SELECT
    *
FROM
    TableWithAllData All
    LEFT JOIN TableWithSomeData Some ON Some.Id = All.id

答案 1 :(得分:2)

有一个名为Json Flattener的{​​{3}}。我想它将解决您的问题。使用Maven将库包含到您的项目中:

<dependency>
  <groupId>com.github.wnameless</groupId>
  <artifactId>json-flattener</artifactId>
 <version>0.6.0</version>
</dependency>

在您的情况下:

  String json = "{ \"key1\": \"value1\", \"key2\": { \"nestedKey1\": \"nested value\", \"nestedKey2\": { \"nestedKey1\": \"nested value\" } } }";
  Map<String, Object> flattenJson = JsonFlattener.flattenAsMap(json);
  System.out.println(flattenJson);

输出:

  

{“ key1”:“ value1”,“ key2.nestedKey1”:“嵌套值”,“ key2.nestedKey2.nestedKey1”:“嵌套值”}