Created
July 15, 2018 19:23
-
-
Save JamieCressey/b1003651844fe938a4ddba18c607ce79 to your computer and use it in GitHub Desktop.
Java POJO to dot notation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FlattenedMapEntry { | |
String key; | |
String value; | |
} | |
public static List<FlattenedMapEntry> flattenMap(String parent, Map<?, ?> map) { | |
List<FlattenedMapEntry> results = new ArrayList<>(); | |
for (Object o : map.entrySet()) { | |
Map.Entry pair = (Map.Entry) o; | |
String key; | |
if (parent == null) { | |
key = pair.getKey().toString(); | |
} else { | |
key = parent + "." + pair.getKey().toString(); | |
} | |
if (pair.getValue() instanceof Map<?, ?>) { | |
results.addAll(flattenMap(key, (Map<?, ?>) pair.getValue())); | |
} else if (pair.getValue() instanceof Set<?> || pair.getValue() instanceof List<?>) { | |
List<?> list = (List<?>) pair.getValue(); | |
for (Object aList : list) { | |
if (aList instanceof Map<?, ?>) { | |
results.addAll(flattenMap(key, (Map<?, ?>) aList)); | |
} else { | |
results.add(FlattenedMapEntry.builder().key(key + "." + aList.toString()).value("").build()); | |
} | |
} | |
} else if (pair.getValue() != null) { | |
String value = pair.getValue().toString(); | |
results.add(FlattenedMapEntry.builder().key(key).value(value).build()); | |
} | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment