Created
November 27, 2019 08:41
-
-
Save shafinmahmud/02b11fb964bd9169c862af543d6d5cb9 to your computer and use it in GitHub Desktop.
Flatten json string to key value map with proper built path
This file contains hidden or 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 JsonFlattener { | |
private final String jsonString; | |
public JsonFlattener(String json) { | |
this.jsonString = json; | |
} | |
public Map<String, String> flattenToMap() throws IOException { | |
Map<String, String> valueMap = new HashMap<>(); | |
ObjectMapper mapper = new ObjectMapper(); | |
JsonNode root = mapper.readTree(this.jsonString); | |
addKeys("", root, valueMap); | |
return valueMap; | |
} | |
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, String> map) { | |
if (jsonNode.isObject()) { | |
ObjectNode objectNode = (ObjectNode) jsonNode; | |
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.getFields(); | |
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + "."; | |
while (iter.hasNext()) { | |
Map.Entry<String, JsonNode> entry = iter.next(); | |
addKeys(pathPrefix + entry.getKey(), entry.getValue(), map); | |
} | |
} else if (jsonNode.isArray()) { | |
ArrayNode arrayNode = (ArrayNode) jsonNode; | |
for (int i = 0; i < arrayNode.size(); i++) { | |
addKeys(currentPath + "[" + i + "]", arrayNode.get(i), map); | |
} | |
} else if (jsonNode.isValueNode()) { | |
ValueNode valueNode = (ValueNode) jsonNode; | |
map.put(currentPath, valueNode.getTextValue()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment