skip to Main Content

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"}}";`

Thanks!

2

Answers


  1. 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);
                }
            }
        }
    }
    
    Login or Signup to reply.
  2. Great answer, John Williams!

    Just a quick note: Due to my current reputation level, I am unable to leave a comment, hence the need for this lengthy remark. Nevertheless, I wanted to mention a minor detail that could prevent a java.lang.StringIndexOutOfBoundsException when truncating strings shorter than 5 characters. To handle this, you can use Math.min with substring to extract up to 5 characters:

    String text = jsonFieldValue.asText();
    objectNode.put(entry.getKey(), text.substring(0, Math.min(text.length(), 5)));
    

    This ensures a safe truncation. Thank you!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search