简体   繁体   中英

How to parse YAML file

I am using Jackson's YAML parser and I want to parse a YAML file without having to manually create a Java class that matches the yaml file. All the examples I can find map it to an object such as here: https://www.baeldung.com/jackson-yaml

The yaml file that is given to me will not always be the same so I need to parse it during runtime, is it possible to achieve this with jackson-yaml?

Like when you are parsing JSON, you can parse into a Map :

Example

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

Output

{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}]}

If you don't know the exact format, you're going to have to parse the data to a tree and process it manually, which can be tedious. I'd use Optional for mapping and filtering.

Example:

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));
}

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM