Converting Nested json into dot notation json

后端 未结 1 1385
遇见更好的自我
遇见更好的自我 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<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));
    
    0 讨论(0)
提交回复
热议问题