javajacksonyamlfasterxml

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


I am currently using faster xml's to convert a yaml to java object, change it and convert it back to yaml.

However I see that when I read the yaml, all the fields are getting populated with these default values. So when I write back the yaml, the default values are populated. How can I avoid this ?

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)

Input yaml :

worktask:
  disable: true

Current Output yaml :

worktask:
  disable: false
  topicName: null
  lockDuration: 0

Desired yaml:

worktask:
  disable: false

Solution

  • Try this:

    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);
    

    Then, use this class:

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

    Fields not given should be null now, and null fields should not be serialized. You might want to look into optional types with Jackson for a more complex setup.