How to map dynamic object hierarchies with YAML

Issue #379 resolved
Michael Rüegg
created an issue


I have a question regarding mapping YAML to an existing object hierarchy. Is it somehow possible to map the following example to make the unit test pass?

interface Node {

class ExtraNode implements Node {
    String foo

class SpecialNode implements Node {
    String bar

class Master {
    List<Node> nodes;

class MyDsl {
    Master master

class YamlSpec extends Specification {

    def 'complex hierarchy'() {
        def constructor = new Constructor(MyDsl.class)
        def yaml = new Yaml(constructor);

        def dsl = (MyDsl) yaml.load("""master:
                                       |  nodes:
                                       |    - extraNode:
                                       |      foo: foo
                                       |    - specialNode:
                                       |      bar: bar""".stripMargin());

        (dsl.master.nodes[1] as SpecialNode).bar == "bar"

Thanks, Michael

Comments (5)

  1. Andrey Somov repo owner

    Sorry, but if you copy-and-paste a lot of code it does not help us to understand the issue. What is the exact problem ? What is the Java test which you expect to work ?

  2. Michael Rüegg reporter

    I've just recognized that I can achieve this with !!prefix notation, e.g.:

        - !!ExtraNode
          foo: foo
        - !!SpecialNode
          bar: bar

    To get rid of fully qualified class names in the YAML, I've stumbled over Are you aware of that? If yes, are there any plans to integrate this feature?

    Thanks for the superb library and keep up the good work :-)

  3. Michael Rüegg reporter

    Excuse me, I've just found the equivalent functionality in your documentation:

    constructor.addTypeDescription(new TypeDescription(ExtraNode.class, "!extraNode"));

    All good, thanks.

  4. Log in to comment