Reputation: 1057
I have a simple YAML data like this that I'm trying to convert to a POJO object called Person
using SnakeYaml.
age: 123
name: Jackson
phone:
number: 123456
Here is the Groovy code that does it.
@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
This creates the Person
object as expected with Tel
inside it.
However, when I try to pass a list of Person
in yaml as follows, I'm getting an error.
- age: 123
name: Jackson
phone:
number: 123456
- age: 234
name: Jackson
phone:
number: 123456
Here is the error I get
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
Upvotes: 1
Views: 2450
Reputation: 3344
I agree with @cfrick, the error that you have in your example is that you are defining a list property, because you say this:
t.putListPropertyType("phone", Tel.class);
but in your Person class you define a single telephone:
class Person{
def name
def age
Tel phone //<-- A SINGLE TELEPHONE!!!
}
To properly correct this, simply modify your Person class to:
class Person{
def name
def age
List<Tel> phone //<-- A REAL LIST OF TELEPHONES!!!
}
Upvotes: 4
Reputation: 1057
I found the answer to my own question. I added explicit separator in the yaml content to make it work.
---
age: 123
name: Jackson
phone:
number: 123456
---
age: 234
name: Jackson
phone:
number: 123456
Upvotes: 0