Parse List / Array from YAML file without root / anchor object

979 views
Skip to first unread message

August Oberhauser

unread,
May 3, 2021, 12:54:17 PM5/3/21
to jackson-user

I have a simple list without a root object:
```
- name: peter
  age: 20
- name: laura
  age: 30
```
class Person {
    @JsonProperty
    public String name;
    @JsonProperty
    public Integer age;
}
How can I convert it to a List<Person> ?

`mapper.readValue(stream, ArrayList.class)` returns a List of LinkedHashMaps. And it is not possible to hand over the type with `ArrayList<Person>.class`

Thank you!

Tatu Saloranta

unread,
May 3, 2021, 11:34:21 PM5/3/21
to jackson-user
Yes, to specify generic (parametric) types you need something else;
`List.class` would basically give `List<?>` which is about same as
`List<Object>`; and `Object` maps to "natural" type from JSON (Map for
JSON Objects).

But there are multiple ways to do what you want.

1. Use TypeReference to pass generic type

List<Person> list = mapper.readValue(input, new
TypeReference<List<Person>>() { });

2. Use Java arrays instead (array types are "native", not generic):

Person[] array = mapper.readValue(input, Person[].class);

3. Use convenience method in ObjectMapper:

List<Person> list = mapper.readerForListOf(Person.class).readValue(input);

Of these, (3) is not well-known as the method was added in Jackson 2.11.

Hope this helps,

-+ Tatu +-

August Oberhauser

unread,
May 4, 2021, 3:06:39 AM5/4/21
to jackson-user
Wow so many Options, which I haven't found while searching through this forum and on github. Helps a lot!

Thank you for answering that fast!
Reply all
Reply to author
Forward
0 new messages