从ObjectMapper中的POJO重写@JsonInclude(Include.NON_NULL) [英] Override @JsonInclude(Include.NON_NULL) from POJO in ObjectMapper

查看:252
本文介绍了从ObjectMapper中的POJO重写@JsonInclude(Include.NON_NULL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题: 在创建ObjectMapper时是否可以覆盖POJO中定义的Include.NON_NULL?

Question: Is it possible to override Include.NON_NULL defined in the POJO while creating the ObjectMapper?

说明:

Explanation:

假设我有一个POJO,如下所示:

Suppose I have a POJO as below:

@JsonInclude(Include.NON_NULL)
class POJO {
  String name;
  String description;
  //Constructors, Getters & Setters, etc
}

还有一个如下的测试类:

And a test class as below:

class Main {
  public static void main(String args[]) {
    POJO p = new POJO();
    ObjectMapper mapper = new ObjectMapper();
     String jsonString = mapper.setSerializationInclusion(Include.ALWAYS)
                               .writerWithDefaultPrettyPrinter()
                               .writeValueAsString(p);
    //jsonString should contain empty name & description fields, but they doesn't
  }
}

推荐答案

您可以使用混入,因为它的优先级高于注释.

You can use a mix-in, since it has priority over annotations.

@JsonInclude(JsonInclude.Include.ALWAYS)
public class MixIn {
}

并将其添加到映射器

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(POJO.class, MixIn.class);

结果将是

{"name":null,"description":null}

这篇关于从ObjectMapper中的POJO重写@JsonInclude(Include.NON_NULL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆