【问题标题】:SnakeYaml - How to convert a yaml to list of pojos with `TypeDescription` configuration set?SnakeYaml - 如何将 yaml 转换为具有“TypeDescription”配置集的 pojo 列表?
【发布时间】:2014-12-14 19:08:26
【问题描述】:

我有一个像这样的简单 YAML 数据,我正在尝试使用 SnakeYaml 将其转换为名为 Person 的 POJO 对象。

age: 123
name: Jackson
phone:
  number: 123456

这是执行此操作的 Groovy 代码。

@ToString
class Person{
    def name
    def age
    Tel phone
}

@ToString
class Tel{
    def number
}

Constructor c = new Constructor(Person.class);
TypeDescription t = new TypeDescription(Person.class);
t.putListPropertyType("phone", Tel.class);
c.addTypeDescription(t);

def person = new Yaml(c).load(input)
println person

这会按预期创建Person 对象,其中包含Tel

但是,当我尝试按如下方式在 yaml 中传递Person 列表时,出现错误。

- age: 123
  name: Jackson
  phone:
    number: 123456
- age: 234
  name: Jackson
  phone:
    number: 123456

这是我得到的错误

Caused by: org.yaml.snakeyaml.error.YAMLException: No suitable constructor with 2 arguments found     for class soapunit.Person
    at org.yaml.snakeyaml.constructor.Constructor$ConstructSequence.construct(Constructor.java:587)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructYamlObject.construct(Constructor.java:340)
... 8 more

【问题讨论】:

    标签: groovy snakeyaml


    【解决方案1】:

    我同意@cfrick,您在示例中遇到的错误是您正在定义一个 list 属性,因为您这样说:

    t.putListPropertyType("phone", Tel.class);
    

    但在您的 Person 类中,您定义了一个 单个 电话:

    class Person{
        def name
        def age
        Tel phone //<-- A SINGLE TELEPHONE!!!
    }
    

    要正确纠正此问题,只需将您的 Person 类修改为:

    class Person{
        def name
        def age
        List<Tel> phone //<-- A REAL LIST OF TELEPHONES!!!
    }
    

    【讨论】:

      【解决方案2】:

      我找到了自己问题的答案。我在 yaml 内容中添加了显式分隔符以使其正常工作。

      ---
      age: 123
      name: Jackson
      phone:
        number: 123456
      ---
      age: 234
      name: Jackson
      phone:
        number: 123456
      

      【讨论】:

      • 这可以解决您的问题,但不能回答原始问题。那么列表有问题吗?
      • @cfrick:确实,看我的回答
      猜你喜欢
      • 2013-09-20
      • 1970-01-01
      • 2016-09-15
      • 2017-09-04
      • 2019-09-30
      • 2012-08-25
      • 1970-01-01
      • 2018-12-31
      相关资源
      最近更新 更多