问题
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).
回答1:
You will need ObjectMapper (from jackson-databind) and YAMLFactory (from jackson-dataformat-yaml).
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
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);
来源:https://stackoverflow.com/questions/54146566/update-the-existing-yaml-file