Converting Nested json into dot notation json

橙三吉。 提交于 2019-11-29 08:25:05

Here is a recursive method that will flatten a nested Map with any depth to the desired dot notation. You can pass it to Jackson's ObjectMapper to get the desired json output:

@SuppressWarnings("unchecked")
public static Map<String, String> flatMap(String parentKey, Map<String, Object> nestedMap)
{
    Map<String, String> flatMap = new HashMap<>();
    String prefixKey = parentKey != null ? parentKey + "." : "";
    for (Map.Entry<String, Object> entry : nestedMap.entrySet()) {
        if (entry.getValue() instanceof String) {
            flatMap.put(prefixKey + entry.getKey(), (String)entry.getValue());
        }
        if (entry.getValue() instanceof Map) {
            flatMap.putAll(flatMap(prefixKey + entry.getKey(), (Map<String, Object>)entry.getValue()));
        }
    }
    return flatMap;
}

Usage:

mapper.writeValue(System.out, flatMap(null, nestedMap));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!