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
Try this.
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 useMath.min
with substring to extract up to 5 characters:This ensures a safe truncation. Thank you!