Java Jackson打印对象,即使设置为非空

Java Jackson打印对象,即使设置为非空,java,jackson,yaml,Java,Jackson,Yaml,程序的一部分将对象转换为YAML字符串。下面是一个最小的示例,它产生的结果与我遇到的问题相同: Main ObjectMapper JSONExportMapper = new ObjectMapper(new YAMLFactory()); JSONExportMapper.setSerializationInclusion(Include.NON_NULL); JSONExportMapper.setSerializationInclusion(Include.NON_EMPTY); St

程序的一部分将对象转换为YAML字符串。下面是一个最小的示例,它产生的结果与我遇到的问题相同:

Main

ObjectMapper JSONExportMapper = new ObjectMapper(new YAMLFactory());
JSONExportMapper.setSerializationInclusion(Include.NON_NULL);
JSONExportMapper.setSerializationInclusion(Include.NON_EMPTY);

String export = JSONExportMapper.writeValueAsString(new Animals());
System.out.println(export);
动物

class Animals {
    public Dog dog;

    public Animals() {
        this.dog = new Dog();
    }
}

class Dog {
    public String sound = "";
}

问题:

如您所见,
Dog
具有属性
sound
,它是一个空字符串。在我的Jackson设置中,我添加了
Include.NON_EMPTY
setSerializationInclusion
,这是为了防止这些属性包含在YAML中,而YAML就是这样做的

包含。非空

---
dog:
  sound: ""
---
dog: {}
带有
Include.NON_EMPTY

---
dog:
  sound: ""
---
dog: {}

问题:

即使对象是完全空的,它仍然包含在YAML中,这对我来说没有意义。在我的例子中,
Animals
Dog
是库中的类,我不应该在库中更改任何代码


有什么是我忽略的吗?如何从生成的YAML字符串中删除完全为空的对象?

看起来没有现成的解决方案,因此我建议您实现自己的序列化程序

public class MyDogSerializer extends StdSerializer<Dog> {

  private static final long serialVersionUID = -4796382940375974812L;

  public MyDogSerializer() {
    super(Dog.class);
  }

  @Override
  public void serialize(Dog value, JsonGenerator gen, SerializerProvider serializers)
      throws IOException, JsonProcessingException {
    if (/** here inspect Dog value for emptiness */) {
      gen.writeObject(null);
    } else {
      ****
    }
  }
}

看起来没有现成的解决方案,所以我建议您应该实现自己的序列化程序

public class MyDogSerializer extends StdSerializer<Dog> {

  private static final long serialVersionUID = -4796382940375974812L;

  public MyDogSerializer() {
    super(Dog.class);
  }

  @Override
  public void serialize(Dog value, JsonGenerator gen, SerializerProvider serializers)
      throws IOException, JsonProcessingException {
    if (/** here inspect Dog value for emptiness */) {
      gen.writeObject(null);
    } else {
      ****
    }
  }
}