json字符串转bean对象
时间: 2023-09-20 21:06:18 浏览: 88
可以使用Java中的Jackson或Gson库来将JSON字符串转换为Java Bean对象。
使用Jackson库:
1. 添加Jackson库的Maven依赖:
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
```
2. 创建Java Bean类,例如:
```java
public class User {
private String name;
private int age;
private List<String> hobbies;
// getters and setters
}
```
3. 使用ObjectMapper将JSON字符串转换为Java Bean对象:
```java
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonString, User.class);
```
使用Gson库:
1. 添加Gson库的Maven依赖:
```xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
```
2. 创建Java Bean类,例如:
```java
public class User {
private String name;
private int age;
private List<String> hobbies;
// getters and setters
}
```
3. 使用Gson将JSON字符串转换为Java Bean对象:
```java
Gson gson = new Gson();
User user = gson.fromJson(jsonString, User.class);
```
阅读全文