Search code examples
javajsonjacksonfasterxml

Limit write size of String with jackson


I have a list of objects with a field "description". This field can be huge (+3000 char) but I use it in the preview (I display only the 100 firsts char).

Is there a way in jackson to limit the size of a String on write ? I only want jackson to crop it to 100 chars. (No bean validation required here).

For exemple, if I have an object like this :

{
    "description" : "bla bla bla bla... + 3000 char"
}

Ideally I want it be cropped like thie :

{
    "description" : bla bla [max 100 chars] bla..."
}

Thank you.


Solution

  • You can write a custom serializer which can crop text if it exceeds a limit as shown below.

    public class DescriptionSerializer extends JsonSerializer<String> {
    
        @Override
        public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
    
            if(value.length() > 100){
                value = value.substring(0, 100) + "...";
            }
            gen.writeString(value);
            
        }
        
    }
    

    And annotate your description field to use this custom serializer

    public class Bean{
       
       @JsonSerialize(using=DescriptionSerializer.class)
       private String description
    
    }