2

I want to update my existing user.yaml file without erasing other objects or properties.

I have been googling for 2 days for a solution, but with no luck.

Actual Output:

name: Test User
age: 30
address:
  line1: My Address Line 1
  line2: Address line 2
  city: Washington D.C.
  zip: 20000
roles:
  - User
  - Editor

Expected Output

name: Test User
age: 30
address:
  line1: Your address line 1
  line2: Your Address line 2
  city: Bangalore
  zip: 560010
roles:
  - User
  - Editor

The above is my yaml file. I want to fetch this yaml file and update the address of the object and write the same information to the new yaml file / existing yaml file. This has to be done without harming other objects (i.e other objects key and values should be retained).

Ishaan Javali
  • 1,711
  • 3
  • 13
  • 23
roshi
  • 68
  • 1
  • 1
  • 5

1 Answers1

5

You will need YAMLMapper (from jackson-databind-yaml) which is the YAML-specific implementation of ObjectMapper (from jackson-databind).

ObjectMapper objectMapper = new YAMLMapper();

Then it is easy: just read the YAML file, modify the contents, and write the YAML file.

Because you have a very simple object structure in your example, you may prefer a quick-and-dirty modeling by using Map<String, Object>.

// read YAML file
Map<String, Object> user = objectMapper.readValue(new File("user.yaml"),
            new TypeReference<Map<String, Object>>() { });
    
// modify the address
Map<String, Object> address = (Map<String, Object>) user.get("address");
address.put("line1", "Your address line 1");
address.put("line2", "Your address line 2");
address.put("city", "Bangalore");
address.put("zip", 560010);
    
// write YAML file
objectMapper.writeValue(new File("user-modified.yaml"), user);

If you would have a more complex object structure, then you should do a more object-oriented modeling by writing some POJO classes (User and Address). But the general idea is still the same:

// read YAML file
User user = objectMapper.readValue(new File("user.yaml"), User.class);
    
// modify the address
Address address = user.getAddress();
address.setLine1("Your address line 1");
address.setLine2("Your address line 2");
address.setCity("Bangalore");
address.setZip(560010);
    
// write YAML file
objectMapper.writeValue(new File("user-modified.yaml"), user);
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
  • Thanks, its working :) . actually I did a lot of research, next time will try to give more information so my question doesn't get down voted :P. quick one: do snakeyaml supports annotation to read properties from .yaml file like jackson do `@JsonProperty("user-report")` – roshi Jan 14 '19 at 07:22