Skip to content

Instantly share code, notes, and snippets.

@mrueegg
Last active June 14, 2017 22:15
Show Gist options
  • Save mrueegg/96ba01ebd7207547ca4012fc1238dc03 to your computer and use it in GitHub Desktop.
Save mrueegg/96ba01ebd7207547ca4012fc1238dc03 to your computer and use it in GitHub Desktop.
SnakeYaml example file
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.NodeId;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class Node {
public String name;
}
class Nodes {
public List<Node> nodes;
}
class Master {
public Nodes nodes;
}
class MyDsl {
public Master master;
}
class MyConstructor extends Constructor {
MyConstructor() {
yamlClassConstructors.put(NodeId.mapping, new NodesConstructor());
}
class NodesConstructor extends Constructor.ConstructMapping {
@Override
protected Object constructJavaBean2ndStep(MappingNode node, Object object) {
Class type = node.getType();
if (type.equals(Master.class)) {
Nodes nodes = new Nodes();
//FIXME: I don't want to construct the whole object tree here, I only want to fill the nodes
nodes.nodes = new ArrayList<>();
Master master = new Master();
master.nodes = nodes;
return master;
} else {
return super.constructJavaBean2ndStep(node, object);
}
}
}
}
public class SnakeYaml {
public static void main(String[] args) throws IOException {
// 1: this is working OK
Yaml yaml = new Yaml();
MyDsl myDsl = yaml.loadAs("master:\n nodes:\n nodes:\n - name: mystage", MyDsl.class);
if(!myDsl.master.nodes.nodes.get(0).name.equals("mystage")) {
throw new AssertionError("Failed with nested nodes");
}
// 2: this is how I need it
Yaml yaml2 = new Yaml(new MyConstructor());
MyDsl myDsl2 = yaml2.loadAs("master:\n nodes:\n - name: mystage", MyDsl.class);
if(!myDsl2.master.nodes.nodes.get(0).name.equals("mystage")) {
throw new AssertionError("Failed with leaving out nodes");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment