5

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.

Oreste Viron
  • 3,592
  • 3
  • 22
  • 34

1 Answers1

7

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

}
baumannalexj
  • 766
  • 1
  • 9
  • 20
Justin Jose
  • 2,121
  • 1
  • 16
  • 15
  • Hello, Thank you for your answer. What if I want to use my DTO in other cases where I need the full description ? – Oreste Viron May 17 '17 at 13:32
  • 1
    You can make use of [Jackson Views](http://www.baeldung.com/jackson-json-view-annotation) as explained in this [question](http://stackoverflow.com/questions/43978724/jackson-json-de-serialization-with-views) – Justin Jose May 18 '17 at 06:32
  • Yes, that will do the job :-) Thank you ! – Oreste Viron May 18 '17 at 07:29