如何在Spring Boot Rest响应中将boolean序列化为String?

时间:2018-04-18 14:30:06

标签: java spring spring-boot

最近我将项目从泽西迁移到Spring Rest。以前布尔字段被序列化为类似success: "true"的字符串,现在它变为没有引号success: true。它不会是一个问题,但旧的应用程序依赖它,不能反序列化。如何在Spring Boot中将布尔值作为String返回?任何spring.jackson.serialization属性?

2 个答案:

答案 0 :(得分:1)

如果您无法访问此字段,请创建一个将对其进行序列化的类:

public class StringBooleanSerializer extends JsonSerializer<Boolean> {

    @Override
    public void serialize(Boolean bool, JsonGenerator generator, SerializerProvider provider) throws IOException {
        generator.writeString(bool ? "true" : "false");
    }
}

将其注册到对象映射器:

    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(new StringBooleanSerializer());

    objectMapper.registerModule(simpleModule);

那就是它。但是,如果您有权访问此字段,则可以执行以下操作:

@JsonSerialize(using=StringBooleanSerializer.class)
private Boolean bool;

如果需要,反序列化也是如此。

答案 1 :(得分:0)

编写自定义序列化程序和反序列化程序,并在该布尔字段上使用以下注释:

@JsonSerialize和@JsonDeserialize。