On Mon, May 3, 2021 at 9:54 AM August Oberhauser <[email protected]> wrote:
>
>
> 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!
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 +-
--
You received this message because you are subscribed to the Google Groups
"jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/jackson-user/CAL4a10ho-b5guyReN8Yc9s%3DC_SOyTC%3DKQv3ttsm6L%3DNg98KneQ%40mail.gmail.com.