Search code examples
javayamlsnakeyaml

Current datetime in yaml by SnakeYaml


The question is, how to specify current datetime in yaml resources file, to make possible yaml.loadAs of SnakeYaml?

Yaml file example.yaml:

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

Loading:

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

Definition of additionalFields in Example.java:

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

Solution

  • You'll need a custom constructor for the !!timestamp tag:

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

    Then, use it when loading:

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