如何将常规表示转储到YAML并避免使用未标记的节点?

时间:2012-05-01 09:35:35

标签: groovy yaml snakeyaml

我想将以下结构转储到YAML文件中:

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

测试用例列表在此类中:

class TestCase {
    String name
    String id
}

我希望它看起来像这样:

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

但最终看起来像这样:

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

我想这与List不是标记数据结构的事实有关,但我无法弄清楚如何获得测试用例的名称来表示对象。提示?

1 个答案:

答案 0 :(得分:5)

TestSuite定义为:

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

让您更接近您想要的结果?我自己没有使用SnakeYaml ......


修改

有一些空闲时间,并提出了这个独立的测试脚本:

@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 )

打印哪些:

name: Carrier Handling and Traffic
testCases:
- id: DCM00000001
  name: Call setup by UE
相关问题