11

I have REST resource that receives JSON object which is a map from user ID to some boolean that indicate if this user had errors.

Since I'm expecting a large number of users, I would like to shrink the size of this JSON by using 1/0 instead of true/false.

I tried and found that during desalinization Jackson will convert 1/0 to true/false successfully, but is there a way to tell Jackson (maybe using annotation?) to serialize this boolean field to 1/0 instead of true/false?

danieln
  • 4,795
  • 10
  • 42
  • 64

2 Answers2

20

Since jackson-databind 2.9, @JsonFormat supports numeric (0/1) boolean serialization (but not deserialization):

@JsonFormat(shape = JsonFormat.Shape.NUMBER)
abstract boolean isActive();

See https://github.com/fasterxml/jackson-databind/issues/1480 which references this SO post.

Brice Roncace
  • 10,110
  • 9
  • 60
  • 69
17

Here is a Jackson JsonSerializer that will serialize booleans as 1 or 0.

public class NumericBooleanSerializer extends JsonSerializer<Boolean> {
    @Override
    public void serialize(Boolean b, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeNumber(b ? 1 : 0);
    }
}

Then annotate boolean fields like so:

@JsonSerialize(using = NumericBooleanSerializer.class)
private boolean fieldName;

Or register it in a Jackson Module:

module.addSerializer(new NumericBooleanSerializer());
Christoffer Hammarström
  • 27,242
  • 4
  • 49
  • 58
  • 1
    Just in case of "Class serializer has no default (no arg) constructor", have a look at https://stackoverflow.com/a/54605694/573034 – Paolo Feb 18 '20 at 12:59