Jackson序列化null或空对象

时间:2019-09-13 10:08:03

标签: java serialization jackson

有一个POJO:

from chainer.datasets import split_dataset_random, TupleDataset

X = [
    [[.04, .46], [.18, .26]],
    [[.32, .28], [.21, .12]]
]
Y = [.4, .5]  # these are the labels for the X instances, in the same order

train, test = split_dataset_random(TupleDataset(X, Y), int(X.shape[0] * .7))

其中B:

class A {
   private B b;
}

是否存在一种使Jackson class B { private String c; } 序列化对象的正确方法,使得A(甚至A.b = null的所有字段都为空或默认)的形式为:< / p>

b

并且不使用自定义序列化程序。较高的POJO实际上很复杂,维护序列化程序带来的麻烦多于好处。

1 个答案:

答案 0 :(得分:2)

将默认属性包含设置为Include.NON_NULL

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;

public class JsonApp {

  public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.setDefaultPropertyInclusion(Include.NON_NULL);

    System.out.println(mapper.writeValueAsString(new A()));
  }
}

class A {
  private B b = new B();

  public B getB() {
    return b;
  }

  public void setB(B b) {
    this.b = b;
  }
}

class B {
  private String c;

  public String getC() {
    return c;
  }

  public void setC(String c) {
    this.c = c;
  }
}

上面的代码显示:

{
  "b" : { }
}