Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

jackson

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?

like image 786
danieln Avatar asked Nov 09 '14 10:11

danieln


Video Answer


2 Answers

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());
like image 104
Christoffer Hammarström Avatar answered Nov 16 '22 02:11

Christoffer Hammarström


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.

like image 35
Brice Roncace Avatar answered Nov 16 '22 03:11

Brice Roncace