Java将JSON数组转为list
时间: 2023-09-14 20:06:29 浏览: 101
可以使用Jackson库的ObjectMapper类中的readValue方法将JSON数组转为List对象。具体实现可以参考以下代码:
```java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class JsonToList {
public static void main(String[] args) throws Exception {
String jsonStr = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Mike\"},{\"id\":3,\"name\":\"Sarah\"}]";
ObjectMapper objectMapper = new ObjectMapper();
List<Person> personList = objectMapper.readValue(jsonStr, new TypeReference<List<Person>>() {});
System.out.println(personList);
}
static class Person {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
}
```
阅读全文