【问题标题】:How do I dump a groovy representation to YAML and avoid having untagged nodes?如何将 groovy 表示转储到 YAML 并避免使用未标记的节点?
【发布时间】:2012-05-10 20:59:50
【问题描述】:

我想将以下结构转储到 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 不是标记数据结构这一事实有关,但我不知道如何获得测试用例的名称来表示对象。提示?

【问题讨论】:

    标签: groovy yaml snakeyaml


    【解决方案1】:

    是否将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
    

    【讨论】:

    • 嗯,我真的不明白这里发生了什么。您覆盖了默认的表示器以不输出元类的名称?没有更简单的方法吗?
    • 不是我能找到的......你能发布你如何输出你在问题中显示的yaml吗?正如我所说,我并没有真正使用过snakeyaml
    • 我只是直接将其转储而不使用 Representer。我宁愿认为我误解了 YAML 本身的某些内容,但我似乎无法完全理解标准,以理解为什么它最终看起来像那样。
    • @Fylke 看起来像snakeyaml 将fully qualified type 放入其中,以便在反序列化 YAML 文件时将其转换回其原始类型......我不得不使用自定义 Representer 作为所有 Groovy 对象有一个元类,在我的测试中,它也被放入了 YAML(所以我的 NonMetaClassRepresenter 将其过滤掉)
    • 啊,现在我开始明白了。所以这就是为什么当我只使用常规的字符串列表而不是自定义的 Groovy 类时它“有效”的原因。那么您的解决方案听起来是唯一明智的选择,谢谢!
    猜你喜欢
    • 2014-12-18
    • 2012-01-29
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多