java - 更新现有的 Yaml 文件

标签 java jackson yaml jackson-databind

我想更新现有的 user.yaml 文件而不删除其他对象或属性。

我已经用谷歌搜索了两天寻找解决方案,但没有运气。

实际输出:

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 的特定于 YAML 的实现(来自 jackson-databind )。

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类( UserAddress )。 但总体思路还是一样的:

// 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);

关于java - 更新现有的 Yaml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54146566/

相关文章:

java - Java中的字符串初始化

Java 8 ToLongFunction 什么时候应该使用它?

java - 在 Spring MVC Controller 中选择 JsonView

java - Spring Boot - 来自 yml 的配置值为空

amazon-web-services - AWS 云形成 : Combining ImportValue and Sub functions causes error

yaml - 资源 SecretsManager 的资源属性 MySecretA 无效,如何在 yml 中创建多个 secret ?

java - 波斯地毯递归

java - 将多个 SOLR 字段合并为一个

java - 如何从json创建java对象

java - jackson 未能反序列化简单的 JSON