如何使用更快的xml操作yaml而不添加字段的默认值



我目前正在使用更快的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);

然后,使用这个类:

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

未给出的字段现在应该是null,null字段不应该序列化。对于更复杂的设置,您可能需要查看Jackson的可选类型。

相关内容

  • 没有找到相关文章

最新更新