我如何使杰克逊不使用默认值序列化图元 [英] How do I make jackson not serialize primitives with default value

查看:89
本文介绍了我如何使杰克逊不使用默认值序列化图元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Jackson中,可以在POJO上使用JsonSerialize注释,以防止对空对象进行序列化(@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)).但是,基元不能设置为null,因此该注释不适用于尚未被触摸且默认为0的int之类的东西.

In Jackson, it is possible to use JsonSerialize annotation on a POJO in order to prevent null objects from being serialized (@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)). Primitives, however, cannot be set to null, so this annotation doesn't work for something like an int that hasn't been touched and defaults to 0.

有没有注释,使我可以说对于此类,除非它们与默认值不同,否则不要序列化原语"或对于此字段,如果其值为X,则不要序列化它" ?

Is there an annotation that would allow me to say something like "For this class, don't serialize primitives unless they are different than their default values" or "For this field, don't serialize it if its value is X"?

推荐答案

如果您使用的是Jackson的最新版本,则可以使用

If you're using a recent version of Jackson you can use JsonInclude.Include.NON_DEFAULT which should work for primitives.

此方法的缺点是将Bean属性设置为其默认值将无效,并且该属性仍将不包括在内:

The downside to this approach is that setting a bean property to its default value will have no effect and the property still won't be included:

@JsonInclude(Include.NON_DEFAULT)
public class Bean {
  private int val;
  public int getVal() { return val; }
  public void setVal(int val) { this.val = val; }
}

Bean b = new Bean();
b.setVal(0);
new ObjectMapper().writeValueAsString(b); // "{}" 

这篇关于我如何使杰克逊不使用默认值序列化图元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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