0

I want to update (no override) my existing yaml file: YAML file looks like this:

firstName: "John"
#text here
lastName: "Doe"
age: 20
#This is important
city: "XYZ"

I have java class:

 ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        String path = "E:/customer.yml";
        Customer customer = objectMapper.readValue(new File(path), Customer.class);
        customer.setAge(50);
        objectMapper.writeValue(new FileWriter(path), customer);

And POJO model:

private String firstName;
private String lastName;
private int age;
//getters setters

How can I update yaml file without overriding it? Actually after run those class, value Age is modified, but other attributes like city is removed. I know, I can update my POJO model, and add city, but in my case, I'm not sure what is in file. I can convert file to String, and replace required data, but It'll not look professional.

Thomas
  • 77
  • 1
  • 5
  • This might help you. [Java - Update the existing Yaml file](https://stackoverflow.com/questions/54146566/update-the-existing-yaml-file) – hbamithkumara Nov 22 '19 at 14:49
  • 1
    A philosophical comment... The yaml was designed for humans to write and edit. So, probably you are doing something wrong if you need this. – kan Nov 23 '19 at 11:04

1 Answers1

0

Because you don't know your POJO structure and don't want to lose any data. I suggest that you should read your file to a map. Create a map in your POJO and try use annotations @JsonAnyGetter, @JsonAnySetter. They should still work because the same library can be used for JSON also.

I don't think there is a possibility to "update". You can just read and override the existing file after that. That means you will lose comments. Unless you will implement your own solution - read the whole file, find char # and save those lines.