这是可能的自定义构造函数和申述:
class CustomObjectConstructor extends Constructor {
public CustomObjectConstructor() {
this.yamlConstructors.put(new Tag("!customObject"), new ConstructCustomObject());
}
private class ConstructCustomObject extends AbstractConstruct {
public Object construct(Node node) {
final Map<Object, Object> values = constructMapping(node);
final String a = (String) values.get("a");
final String b = (String) values.get("b");
final String c = (String) values.get("c");
return new CustomObject(a + ":" + b + "/" + c);
}
}
}
您可以使用它像这样:
Yaml yaml = new Yaml(new CustomObjectConstructor());
CustomObject myObject =
(CustomObject) yaml.load("!customObject\na: 1\nb: 2\nc: 3");
当然,这需要细化处理错误的情况下,但它显示了一般理念。要将对象转储为映射,您可以在此定义代表类似于代码的表示器。有关更多信息,请参阅documentation。