取自snakeyaml 项目WIKI。例子在这里。
如何解析 JodaTime
由于 JodaTime 不是 JavaBean(因为它没有空的构造函数),因此在解析时需要一些额外的处理:
private class ConstructJodaTimestamp extends ConstructYamlTimestamp {
public Object construct(Node node) {
Date date = (Date) super.construct(node);
return new DateTime(date, DateTimeZone.UTC);
}
}
当 JodaTime 实例是 JavaBean 属性时,您可以使用以下内容:
Yaml y = new Yaml(new JodaPropertyConstructor());
class JodaPropertyConstructor extends Constructor {
public JodaPropertyConstructor() {
yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct());
}
class TimeStampConstruct extends Constructor.ConstructScalar {
@Override
public Object construct(Node nnode) {
if (nnode.getTag().equals("tag:yaml.org,2002:timestamp")) {
Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP);
Date date = (Date) dateConstructor.construct(nnode);
return new DateTime(date, DateTimeZone.UTC);
} else {
return super.construct(nnode);
}
}
}
}