使用ObjectMapper处理同一个类的序列化中的空值?

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

这里。 我正在寻找有关使用 ObjectMapper 序列化对象的解决方案。网上类似的问题还有很多,但没有找到完全符合我情况的。造成这种情况的原因是由于两个不同的外部系统,而且这样的类有很多。为每个单独定义序列化方法有点麻烦且有风险。我需要以两种方式序列化一个类:忽略空值和不忽略空值。两者都可能会用到,所以不能直接选其一。

有没有办法在方法级别控制是否忽略空值? 例如:

// @JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
    String name;
    Integer age;
    // When email is null,
    // sometimes the email must exist in the final string,
    // even if it is empty. Other times, I need it to be absent.
    String email;
    /// ===== omitted getter / setter =====

    public static void main(String[] args) throws JsonProcessingException {
        System.out.println(new ObjectMapper().writeValueAsString(new User().setAge(11).setName("Christian")));
    }
}

是否有比针对每种情况单独实现序列化方法更好的方法? 对于任何建议和文档链接,我将非常感激。

java jackson
1个回答
0
投票

您可以根据用例使用 2 个对象映射器实例。

第一个具有默认设置,第二个忽略空值

 ObjectMapper mapper = new ObjectMapper();  
 mapper.setSerializationInclusion(Include.NON_NULL);
© www.soinside.com 2019 - 2024. All rights reserved.