package com.mkyong; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Arrays; import java.util.List; public class JacksonArrayExample { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper(); String json = "[{"name":"mkyong", "age":37}, {"name":"fong", "age":38}]"; try { // 1. convert JSON array to Array objects Person[] pp1 = mapper.readValue(json, Person[].class); System.out.println("JSON array to Array objects..."); for (Person person : pp1) { System.out.println(person); } // 2. convert JSON array to List of objects List<Person> ppl2 = Arrays.asList(mapper.readValue(json, Person[].class)); System.out.println(" JSON array to List of objects"); ppl2.stream().forEach(x -> System.out.println(x)); // 3. alternative List<Person> pp3 = mapper.readValue(json, new TypeReference<List<Person>>() {}); System.out.println(" Alternative..."); pp3.stream().forEach(x -> System.out.println(x)); } catch (IOException e) { e.printStackTrace(); } } }
import lombok.Data; import lombok.ToString; @Data @ToString public class Person { private String name; private Integer age; }
maven依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency>
当你的返回数据类型复杂的时候,可以用TypeReference轻松指定返回类型。
输出:
转载自:https://www.mkyong.com/java/jackson-convert-json-array-string-to-list/