SnakeYaml 在 yaml 中的当前日期时间

Current datetime in yaml by SnakeYaml

问题是,如何在yaml资源文件中指定当前日期时间,才能实现SnakeYaml的yaml.loadAs?

Yaml 文件example.yaml:

additionalFields:
    eventtype: userchange
    listname: default
    timestamp: !!timestamp now

正在加载:

    try( InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("example.yaml")) {
        Yaml yaml = new Yaml();
        topSettings = yaml.loadAs( in, Example.class );
    }

additionalFieldsExample.java中的定义:

private Map<String, Object> additionalFields = new HashMap<String, Object>();

您需要为 !!timestamp 标签自定义构造函数:

class TsConstructor extends Constructor {
    public TsConstructor() {
        this.yamlConstructors.put(new Tag("yaml.org,2002:timestamp"),
                new ConstructTimestamp());
    }

    private class ConstructTimestamp extends AbstractConstruct {
        public Object construct(Node node) {
            String val = (String) constructScalar(node);
            if ("now".equals(val)) {
                return Instant.now();
            } else {
                return Instant.parse(val);
            }
        }
    }
}

然后,加载时使用它:

Yaml yaml = new Yaml(new TsConstructor());
topSettings = yaml.loadAs( in, Example.class );