更新时间:2023-12-02 21:34:10
您将需要 jackson-databind
)
和 YAMLFactory
(来自 jackson-dataformat-yaml
)
You will need ObjectMapper
(from jackson-databind
)
and YAMLFactory
(from jackson-dataformat-yaml
).
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
这很容易:只需读取YAML文件,修改内容并写入YAML文件.
Then it is easy: just read the YAML file, modify the contents, and write the YAML file.
由于示例中的对象结构非常简单,
您可能更喜欢使用Map<String, Object>
进行快速建模.
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);
如果您的对象结构更复杂,
那你应该做一个更面向对象的建模
通过编写一些 POJO 类(User
和Address
).
但是总体思路还是一样的:
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);