Last active
December 21, 2016 23:05
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.
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
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