I have a dynamic nested json string and I wanted to limit the string value of all keys to have max length of 5 chars.
Using: Java fasterxml.jackson
For Json String like below:
String inputJsonString = "{\"key1\":\"bla bla bla bla\",\"key2\":{\"key21\":\"bla bla bla\"}}";
I wanted this result:
String outputJsonString = "{\"key1\":\"bla b\",\"key2\":{\"key21\":\"bla b\"}}";
For Json String like this:
String inputJsonString = "{\"fname\":\"bla bla bla bla\",\"address\":{\"street\":\"bla bla bla\"}}";
I wanted this result:
String outputJsonString = "{\"fname\":\"bla b\",\"address\":{\"street\":\"bla b\"}}";
Try this.
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String inputJsonString = "{\"key1\":\"bla bla bla bla\",\"key2\":{\"key21\":\"bla bla bla\"},\"key3\":[{\"key21\":\"bla bla bla\"}]}";
System.out.println(inputJsonString);
JsonNode jsonNode = mapper.readTree(inputJsonString);
truncateStringValues(jsonNode);
System.out.println(jsonNode);
}
private static void truncateStringValues(JsonNode jsonNode) throws JsonMappingException, JsonProcessingException {
if (jsonNode.isArray()) {
for (JsonNode arrayItem : jsonNode) {
truncateStringValues(arrayItem);
}
} else if (jsonNode.isObject()) {
Iterator<Entry<String, JsonNode>> fields = jsonNode.fields();
while (fields.hasNext()) {
Entry<String, JsonNode> jsonField = fields.next();
JsonNode jsonFieldValue = jsonField.getValue();
if (!jsonFieldValue.isContainerNode()) {
((ObjectNode) jsonNode).put(jsonField.getKey(), jsonFieldValue.asText().substring(0, 5));
} else {
truncateStringValues(jsonFieldValue);
}
}
}
}