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
source to share
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());
source to share