ObjectMapper - 向 yaml 文件添加新值

ObjectMapper - add new value to yaml file

下面是我的 yaml 文件。要求是在 "paths" 下添加新行“2.log”。现在我正在阅读 yaml 文件 Map<String, List<Map<String, Map<String, String>>>>.

我的代码:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Map<String, List<Map<String, Map<String, String>>>> obj = mapper
                        .readValue(new File("filebeat.yml"), Map.class);

obj.get("filebeat.prospectors").get(0).get("paths");
 // syso is : paths: [1.log]

现在我需要为 "paths" 添加新元素。

原始 YAML 文件:

filebeat.prospectors:
- input_type: "log"
  paths: 
    - "1.log"
  fields:
    log_type: "log1"
output.logstash:
  hosts:
  - "127.0.0.1:5044"

所需的 YAML 文件:

filebeat.prospectors:
- input_type: "log"
  paths: 
    - "1.log"
    - "2.log"
  fields:
    log_type: "log1"
output.logstash:
  hosts:
  - "127.0.0.1:5044"

问题中YAML的结构与数据结构不对应。例如 input_type 是正确的列表元素,但 output.logstash 是映射条目的键,它与 Map<String, List< 这样的结构冲突。因为这是一个容易犯的错误,所以我建议解析成树并进行修改。这更干净并且可以按预期工作:

JsonNode tree = mapper.readTree(new File("filebeat.yml"));
((ArrayNode) tree.get("filebeat.prospectors").get(0).get("paths")).add("2.log");
System.out.println(tree.get("filebeat.prospectors").get(0).get("paths"));

ArrayNode and JsonNode. JsonNode is immutable and you need to cast to ObjectNode or if appropriate ArrayNode to modify or add elements. readTree parses documents into a special tree data structure that can represent any valid JSON, YAML, XML without requiring a Java class with a structure that matches the document. More details here and here

的文档