如何在不添加字段默认值的情况下使用 fasterxml 操作 yaml

How to manipulate a yaml using fasterxml without adding default value of field's

我目前正在使用更快的 xml 将 yaml 转换为 java 对象,更改它并将其转换回 yaml。

但是我看到,当我阅读 yaml 时,所有字段都填充了这些默认值。因此,当我写回 yaml 时,会填充默认值。我怎样才能避免这种情况?

public class workTask {

  private boolean disable;
  private String name;
  private long duration;
}
private static final ObjectMapper mapper =
      new ObjectMapper(new YAMLFactory().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES));
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

mapper.readValue(string, Worker.class);
// .. do manipulation
mapper.writeValueAsString(src)

输入 yaml :

worktask:
  disable: true

当前输出 yaml:

worktask:
  disable: false
  topicName: null
  lockDuration: 0

所需的 yaml:

worktask:
  disable: false

试试这个:

YAMLMapper mapper = new YAMLMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
YAMLFactory factory = new YAMLFactory(mapper);
factory.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
ObjectMapper mapper = new ObjectMapper(factory);

然后,使用这个 class:

public class Worker {
  private Boolean disable;
  private String name;
  private Long duration;
}

未给出的字段现在应 null,并且 null 字段不应序列化。您可能需要查看 optional types with Jackson 以获得更复杂的设置。