JSON是Java EE 8中自带的一个JSON处理库,可以方便地将Json数据转换为Java对象。需要先在pom.xml中添加JSON库的依赖:
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.4</version>
</dependency>
然后使用JsonReader和JsonArray将Json数据转换为List对象
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String json = "[{\"name\":\"Tom\",\"age\":18},{\"name\":\"Jerry\",\"age\":20}]";
JsonReader jsonReader = Json.createReader(new StringReader(json));
JsonArray jsonArray = jsonReader.readArray();
List<Person> personList = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
String name = jsonArray.getJsonObject(i).getString("name");
int age = jsonArray.getJsonObject(i).getInt("age");
Person person = new Person();
person.setName(name);
person.setAge(age);
personList.add(person);
}
System.out.println(personList);
}
}
class Person {
private String name;
private int age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}