在Java中JSON转成实体类的list,代码实现
时间: 2024-02-03 19:15:20 浏览: 73
假设你有如下的 JSON 数据:
```json
[
{
"id": 1,
"name": "Alice",
"age": 20
},
{
"id": 2,
"name": "Bob",
"age": 25
}
]
```
你可以通过以下代码将其转换为实体类的 List:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
public class JsonToListExample {
public static void main(String[] args) throws IOException {
String json = "[{\"id\":1,\"name\":\"Alice\",\"age\":20},{\"id\":2,\"name\":\"Bob\",\"age\":25}]";
ObjectMapper mapper = new ObjectMapper();
List<User> users = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, User.class));
System.out.println(users);
}
}
class User {
private int id;
private String name;
private int age;
// getters and setters
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
这里使用了 Jackson 库来进行 JSON 的转换,需要在项目中添加以下依赖:
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
```
运行以上代码会输出:
```
[User{id=1, name='Alice', age=20}, User{id=2, name='Bob', age=25}]
```
阅读全文