Search code examples
groovyyamlsnakeyaml

How do I dump a groovy representation to YAML and avoid having untagged nodes?


I want to dump the following structure to a YAML file:

public class TestSuite {
    String name
    List testCases = []
}

Where the list of test cases are this class:

class TestCase {
    String name
    String id
}

What I want it to look like is this:

name: Carrier Handling and Traffic
testCases:
- name: Call setup by UE
  id: DCM00000001

But it ends up looking like this:

name: Carrier Handling and Traffic
testCases:
- !!com.package.path.TestCase
  name: Call setup by UE
  id: DCM00000001

I guess it has to do with the fact that the List isn't a tagged data structure but I can't figure out how I can get the name of the test case to represent the object. Tips?


Solution

  • Does defining TestSuite as:

    public class TestSuite {
        String name
        List<TestCase> testCases = []
    }
    

    Get you closer to the result you want? Not used SnakeYaml myself though...


    Edit

    Had some free time, and came up with this standalone test script:

    @Grab( 'org.yaml:snakeyaml:1.10' )
    import org.yaml.snakeyaml.Yaml
    import org.yaml.snakeyaml.representer.Representer
    import java.beans.IntrospectionException
    import org.yaml.snakeyaml.introspector.Property
    
    public class TestSuite {
        String name
        List<TestCase> testCases = []
    }
    
    class TestCase {
        String name
        String id
    }
    
    class NonMetaClassRepresenter extends Representer {
      protected Set<Property> getProperties( Class<? extends Object> type ) throws IntrospectionException {
        super.getProperties( type ).findAll { it.name != 'metaClass' }
      }
    }
    
    TestSuite suite = new TestSuite( name:'Carrier Handling and Traffic' )
    suite.testCases << new TestCase( name:'Call setup by UE', id:'DCM00000001' ) 
    
    println new Yaml( new NonMetaClassRepresenter() ).dumpAsMap( suite )
    

    Which prints:

    name: Carrier Handling and Traffic
    testCases:
    - id: DCM00000001
      name: Call setup by UE