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! Tatu Saloranta schrieb am Dienstag, 4. Mai 2021 um 05:34:21 UTC+2: > 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/8c080148-9280-43b4-81ca-a3aa6ab1c00dn%40googlegroups.com.
