[英]Update the existing Yaml file
我想在不删除其他对象或属性的情况下更新我现有的user.yaml
文件。
我已经用谷歌搜索了 2 天的解决方案,但没有运气。
实际输出:
name: Test User
age: 30
address:
line1: My Address Line 1
line2: Address line 2
city: Washington D.C.
zip: 20000
roles:
- User
- Editor
预期产出
name: Test User
age: 30
address:
line1: Your address line 1
line2: Your Address line 2
city: Bangalore
zip: 560010
roles:
- User
- Editor
以上是我的yaml文件。 我想获取这个 yaml 文件并更新对象的地址并将相同的信息写入新的 yaml 文件/现有的 yaml 文件。 这必须在不损害其他对象的情况下完成(即应保留其他对象的键和值)。
您将需要YAMLMapper
(来自jackson-databind-yaml
),它是ObjectMapper
(来自jackson-databind
)的 YAML 特定实现。
ObjectMapper objectMapper = new YAMLMapper();
那么就很简单了:只需读取 YAML 文件,修改内容,然后编写 YAML 文件即可。
因为您的示例中有一个非常简单的对象结构,所以您可能更喜欢使用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
)来进行更面向对象的建模。 但总体思路还是一样的:
// 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.