如何解析YAML文件

时间:2020-03-26 22:51:45

标签: java jackson yaml

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

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

2 个答案:

答案 0 :(得分:3)

就像解析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}]}

答案 1 :(得分:3)

如果您不知道确切的格式,则必须将数据解析为树并手动处理,这可能很繁琐。我会使用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}