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

I have a REST resource that receives a JSON object that is a map from a user id to some boolean indicating whether this user has had errors.

Since I expect a lot of users, I would like to reduce the size of this JSON using 1/0 instead of true / false.

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

+3


source to share


1 answer


Here is Jackson JsonSerializer

that will serialize boolean values โ€‹โ€‹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 we annotate the boolean fields, for example:



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

      

Or register it with Jackson Module

:

module.addSerializer(new NumericBooleanSerializer());

      

+8


source







All Articles