java 中JSONObject转list
时间: 2023-11-19 11:06:09 浏览: 94
可以使用Java中的JSONArray实现将JSONObject转换成List。具体步骤如下:
1. 将JSONObject转换成JSONArray。
2. 遍历JSONArray,将每个元素转换为Java对象并添加到List中。
示例代码如下:
```java
import org.json.*;
public class JsonToList {
public static void main(String[] args) {
String jsonStr = "{\"students\": [{\"name\": \"Alice\", \"age\": 18}, {\"name\": \"Bob\", \"age\": 20}]}";
try {
JSONObject obj = new JSONObject(jsonStr);
JSONArray arr = obj.getJSONArray("students");
List<Student> studentList = new ArrayList<>();
for (int i = 0; i < arr.length(); i++) {
JSONObject studentObj = arr.getJSONObject(i);
String name = studentObj.getString("name");
int age = studentObj.getInt("age");
studentList.add(new Student(name, age));
}
System.out.println(studentList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
阅读全文