Converting Nested json into dot notation json

后端 未结 1 1386
遇见更好的自我
遇见更好的自我 2020-12-18 11:29

I have a service from where I get a json string response like as shown below

{
  \"id\": \"123\",
  \"name\": \"John\"
}

I consume the rest

1条回答
  •  抹茶落季
    2020-12-18 12:16

    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 flatMap(String parentKey, Map nestedMap)
    {
        Map flatMap = new HashMap<>();
        String prefixKey = parentKey != null ? parentKey + "." : "";
        for (Map.Entry 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)entry.getValue()));
            }
        }
        return flatMap;
    }
    

    Usage:

    mapper.writeValue(System.out, flatMap(null, nestedMap));
    

    0 讨论(0)
提交回复
热议问题