【问题标题】:How to parse YAML file如何解析 YAML 文件
【发布时间】:2020-03-26 22:51:45
【问题描述】:

我正在使用 Jackson 的 YAML 解析器,我想解析一个 YAML 文件而无需手动创建一个与 yaml 文件匹配的 Java 类。我能找到的所有示例都将其映射到一个对象,例如:https://www.baeldung.com/jackson-yaml

提供给我的 yaml 文件并不总是相同,所以我需要在运行时解析它,是否可以使用 jackson-yaml 来实现?

【问题讨论】:

  • 如果你不想解析成Java类,你想解析成什么?
  • 你的意思是在运行时你可能会被传递不同的文件并且不能在源代码中硬编码文件路径?

标签: java jackson yaml


【解决方案1】:

如果您不知道确切的格式,您将不得不将数据解析为树并手动处理,这可能很乏味。我会使用 Optional 进行映射和过滤。

例子:

public static final String YAML = "invoice: 34843\n"
    + "date   : 2001-01-23\n"
    + "product:\n"
    + "    - sku         : BL394D\n"
    + "      quantity    : 4\n"
    + "      description : Basketball\n"
    + "      price       : 450.00\n"
    + "    - sku         : BL4438H\n"
    + "      quantity    : 1\n"
    + "      description : Super Hoop\n"
    + "      price       : 2392.00\n"
    + "tax  : 251.42\n"
    + "total: 4443.52\n";

public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    JsonNode jsonNode = objectMapper.readTree(YAML);

    Optional.of(jsonNode)
            .map(j -> j.get("product"))
            .filter(ArrayNode.class::isInstance)
            .map(ArrayNode.class::cast)
            .ifPresent(projectArray -> projectArray.forEach(System.out::println));
}

输出:

{"sku":"BL394D","quantity":4,"description":"Basketball","price":450.0}
{"sku":"BL4438H","quantity":1,"description":"Super Hoop","price":2392.0}

【讨论】:

    【解决方案2】:

    就像解析 JSON 时一样,可以解析成Map

    例子

    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    @SuppressWarnings("unchecked")
    Map<String, Object> map = mapper.readValue(new File("test.yaml"), Map.class);
    System.out.println(map);
    

    test.yaml

    orderNo: A001
    date: 2019-04-17
    customerName: Customer, Joe
    orderLines:
        - item: No. 9 Sprockets
          quantity: 12
          unitPrice: 1.23
        - item: Widget (10mm)
          quantity: 4
          unitPrice: 3.45
    

    输出

    {orderNo=A001, date=2019-04-17, customerName=Customer, Joe, orderLines=[{item=No. 9 Sprockets, quantity=12, unitPrice=1.23}, {item=Widget (10mm), quantity=4, unitPrice=3.45}]}
    

    【讨论】:

      猜你喜欢
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 2010-12-18
      • 2017-06-03
      相关资源
      最近更新 更多