Java – Jackson – serialize Boolean to 1 / 0 instead of true / false

I have a rest resource to receive a JSON object, which is a mapping from a user ID to a Boolean value, indicating whether the user has an error

Since I expect a large number of users, I want to reduce the size of this JSON by using 1 / 0 instead of true / false

I tried and found that Jackson would successfully convert 1 / 0 to true / false in the desalination process, but is there any way to tell Jackson Serialize this Boolean field to 1 / 0 instead of true / false?

Solution

This is a Jackson jsonserializer that serializes Boolean values to 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 the Boolean field as follows:

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

Or register in the Jackson module:

module.addSerializer(new NumericBooleanSerializer());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>