你会需要YAMLMapper http://fasterxml.github.io/jackson-dataformat-yaml/javadoc/2.7/com/fasterxml/jackson/dataformat/yaml/YAMLMapper.html (from jackson-databind-yaml https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml)
这是 YAML 特定的实现ObjectMapper https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html (from jackson-databind https://mvnrepository.com/artifact/com.fasterxml.jackson.core/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 https://stackoverflow.com/questions/3527264/how-to-create-a-pojo类(User
and 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);