JSONArray 转list
时间: 2024-02-06 16:02:07 浏览: 83
java json 转换
以下是将JSONArray转换为List的示例代码:
```java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 示例JSONArray
JSONArray jsonArray = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("code", "编码1");
obj1.put("name", "名称1");
jsonArray.add(obj1);
JSONObject obj2 = new JSONObject();
obj2.put("code", "编码2");
obj2.put("name", "名称2");
jsonArray.add(obj2);
// JSONArray转List
List<User> userList = jsonArray.toJavaList(User.class);
System.out.println("JSONArray转List:" + userList);
}
}
class User {
private String code;
private String name;
// 省略getter和setter方法
@Override
public String toString() {
return "User{" +
"code='" + code + '\'' +
", name='" + name + '\'' +
'}';
}
}
```
输出结果:
```
JSONArray转List:[User{code='编码1', name='名称1'}, User{code='编码2', name='名称2'}]
```
阅读全文