更新现有的Yaml文件

更新现有的Yaml文件

本文介绍了更新现有的Yaml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不删除其他对象或属性的情况下更新现有的user.yaml文件.

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

我已经搜寻了2天了,但是没有运气.

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

实际输出:

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文件.必须在不损害其他对象的情况下完成此操作(即,应保留其他对象的键和值).

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).

推荐答案

您将需要 ObjectMapper (来自 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 类(UserAddress).但是总体思路还是一样的:

If you would have a more complex object structure,then you should do a more object-oriented modelingby 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);

这篇关于更新现有的Yaml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 03:28