忽略空值的只读类的序列化 – 无需创建自定义 ObjectMapper

问题描述 投票:0回答:1

假设,我希望杰克逊在序列化这个特定对象时忽略空值。我尝试了这个(但请记住,正在序列化的实际类是只读的)

@RestController
public class SomeObjectController {
    @GetMapping("/some-object-with-no-nulls")
    @JsonInclude(content = JsonInclude.Include.NON_NULL)
    public Mono<SomeObject> getSomeObject() {
        return new SomeObject(null, "string");
    }
    @NoArgsContructor
    @Getter
    @Setter
    public class SomeObject {
        private String firstField;
        private String secondField;
    }
}

然而,这不起作用

{
    firstField: null,
    secondField: "string"
}

预期结果是:

{
    secondField: "string"
}

如果我注册自定义,我就会得到我想要的东西

ObjectMapper
。但我可能不一定希望我的所有端点都有这种行为

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }

我还想避免编写自定义序列化器。也许有可能,但我更喜欢声明式解决方案(同时意识到它们的缺点)

我该怎么办?

java jackson jackson-databind
1个回答
0
投票

您可以在 SomeObject 类之上添加 json include

© www.soinside.com 2019 - 2024. All rights reserved.