如何将数组json字符串转为List对象
时间: 2023-04-08 07:01:06 浏览: 153
可以使用Gson库来实现将数组json字符串转为List对象的功能。具体实现步骤如下:
1. 导入Gson库的jar包。
2. 创建Gson对象。
3. 使用Gson对象的fromJson方法将json字符串转为List对象。
示例代码如下:
```
import com.google.gson.Gson;
import java.util.List;
public class Test {
public static void main(String[] args) {
String jsonStr = "[{\"name\":\"张三\",\"age\":20},{\"name\":\"李四\",\"age\":21}]";
Gson gson = new Gson();
List<User> userList = gson.fromJson(jsonStr, new TypeToken<List<User>>(){}.getType());
for (User user : userList) {
System.out.println(user.getName() + " " + user.getAge());
}
}
}
class User {
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; }
}
```
输出结果为:
```
张三 20
李四 21
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)