我正在寻找使用SnakeYAML的自定义结构,我不知道如何实现嵌套.我正在使用这个例子作为参考.
在链接的示例中,相关的YAML和Construct是,
- !circle
center: {x: 73, y: 129}
radius: 7
Run Code Online (Sandbox Code Playgroud)
private class ConstructCircle extends AbstractConstruct {
@SuppressWarnings("unchecked")
public Object construct(Node node) {
MappingNode mnode = (MappingNode) node;
Map<Object, Object> values = constructMapping(mnode);
Circle circle = new Circle((Map<String, Integer>) values.get("center"), (Integer) values.get("radius"));
return circle;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,让我们改变YAML,
- !circle
center: !point
x: 73
y: 129
radius: 7
Run Code Online (Sandbox Code Playgroud)
我想用另一个AbstractConstruct来解析该!point对象,但是在ConstructCircle上下文中进行.我对这种Construct/Node关系的理解非常不稳定,我对如何在自定义构造函数中使用自定义构造函数感到茫然.有什么想法或资源吗?
我写了一个快速而肮脏的代码customConstructMapping()来解析您的嵌套构造 YAML。
public Map<Object, Object> customConstructMapping(MappingNode mnode) {
Map<Object, Object> values = new HashMap<Object, Object>();
Map<String, Integer> center = new HashMap<String, Integer>();
List<NodeTuple> tuples = mnode.getValue();
for (NodeTuple tuple : tuples) {
ScalarNode knode = (ScalarNode) tuple.getKeyNode();
String key = knode.getValue();
Node vnode = tuple.getValueNode();
if (vnode instanceof MappingNode) {
MappingNode nvnode = (MappingNode) vnode;
if ("!point".equals(nvnode.getTag().getValue())) {
List<NodeTuple> vtuples = nvnode.getValue();
for (NodeTuple vtuple : vtuples) {
ScalarNode vknode = (ScalarNode) vtuple.getKeyNode();
ScalarNode vvnode = (ScalarNode) vtuple.getValueNode();
Integer val = Integer.parseInt(vvnode.getValue());
center.put(vknode.getValue(), val);
}
values.put(key, center);
}
} else if (vnode instanceof ScalarNode) {
Integer val = Integer.parseInt(((ScalarNode) vnode).getValue());
values.put(key, val);
}
}
return values;
}
Run Code Online (Sandbox Code Playgroud)