danieln
danieln

Reputation: 4973

Jackson - Serialize boolean to 1/0 instead of true/false

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?

Upvotes: 11

Views: 19837

Answers (2)

Brice Roncace
Brice Roncace

Reputation: 10650

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.

Upvotes: 20

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());

Upvotes: 17

Related Questions