ObjectMapper - YAML 解析 - 忽略注释

问题描述 投票:0回答:1

YAML 文件示例

---
# Author : John Doe
# Updated Date: 6/21/2024 4:23:22 PM
# Status: Deployed.
name: "stack overflow"
version: 5

解析yaml文件时,如何忽略以#开头的注释行

ObjectMapper mapper = new ObjectMapper(); 
MyDoc myDoc = mapper.readValue(response.toString(), MyDoc.class);
java parsing yaml comments objectmapper
1个回答
0
投票
package nl.swilvan;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {

        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        var ex = mapper.reader().forType(Example.class).readValue(new File("src/main/resources/example.yml"));

        System.out.println(mapper.writer().writeValueAsString(ex));
    }

    public static class Example {

        String name;

        public int getVersion() {
            return version;
        }

        public void setVersion(int version) {
            this.version = version;
        }

        int version;


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

似乎对我有用,我添加了 https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml/2.17.1 作为依赖项。 example.yml 是您的示例 yml

© www.soinside.com 2019 - 2024. All rights reserved.