Limit write size of String with jackson
Asked Answered
V

1

6

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.

Virchow answered 17/5, 2017 at 7:30 Comment(0)
H
8

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

}
Hammett answered 17/5, 2017 at 9:1 Comment(3)
Hello, Thank you for your answer. What if I want to use my DTO in other cases where I need the full description ?Virchow
You can make use of Jackson Views as explained in this questionHammett
Yes, that will do the job :-) Thank you !Virchow

© 2022 - 2024 — McMap. All rights reserved.