How to parse YAML file

pepe1 :

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?

Sean Patrick Floyd :

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}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360848&siteId=1