這是可能的自定義構造函數和申述:
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。