简体   繁体   English

Jackson - 将布尔值序列化为1/0而不是true / false

[英]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. 我有REST资源接收JSON对象,该对象是从用户ID到某个布尔值的映射,指示此用户是否有错误。

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. 由于我期待大量用户,我想通过使用1/0而不是true / false来缩小此JSON的大小。

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? 我试过并发现在脱盐过程中杰克逊会成功地将1/0转换为真/假,但是有没有办法告诉杰克逊(可能使用注释?)将这个布尔字段序列化为1/0而不是真/假?

Here is a Jackson JsonSerializer that will serialize booleans as 1 or 0 . 这是一个Jackson JsonSerializer ,它将布尔值序列化为10

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注册:

module.addSerializer(new NumericBooleanSerializer());

Since jackson-databind 2.9, @JsonFormat supports numeric (0/1) boolean serialization (but not deserialization): 从jackson-databind 2.9开始, @JsonFormat支持数字(0/1)布尔序列化(但不支持反序列化):

@JsonFormat(shape = JsonFormat.Shape.NUMBER)
abstract boolean isActive();

See https://github.com/fasterxml/jackson-databind/issues/1480 which references this SO post. 请参阅https://github.com/fasterxml/jackson-databind/issues/1480 ,其中引用了此SO帖子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM