Skip to content

Instantly share code, notes, and snippets.

@stmcallister
Last active December 21, 2016 23:05
Show Gist options
  • Save stmcallister/92d0b4c2355a490ffed008cfbda69063 to your computer and use it in GitHub Desktop.
Save stmcallister/92d0b4c2355a490ffed008cfbda69063 to your computer and use it in GitHub Desktop.
I have a program that needed to consume a second API where the field names in the JSON response could be capitalized, or might not. We're using JsonNode to parse the responses, and this is a solution I came up with. I'm posting it here as it may help others - or could be improved with feedback.
private static JsonNode lowercaseNodeNames(JsonNode node) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode loweredNode = mapper.createObjectNode();
Iterator<String> fieldNames = node.fieldNames();
while (fieldNames.hasNext()) {
String currentName = fieldNames.next();
JsonNode currentValue = null;
if (node.get(currentName).isObject()) {
// checking for nestedNode in currentNode
JsonNode nestedNode = node.get(currentName);
currentValue = lowercaseNodeNames(nestedNode);
} else if (node.get(currentName).isArray()) {
ArrayNode arrayNode = mapper.createArrayNode();
for (int i = 0; i < node.get(currentName).size(); i++) {
arrayNode.add(lowercaseNodeNames(node.get(currentName).get(i)));
}
currentValue = arrayNode;
} else {
currentValue = node.get(currentName);
}
// lowercase only the first character of the name
loweredNode.put(Character.toString(currentName.charAt(0)).toLowerCase() + currentName.substring(1), currentValue);
}
return loweredNode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment