使用Java将下述{ "class": "1A", "teacher": "Mr. Smith", "students": [ { "name": "Alice", "age": 12, "gender": "female" }, { "name": "Bob", "age": 13, "gender": "male" } ] }json串中的students数组转换成对象并打印对象
时间: 2023-07-03 08:27:06 浏览: 43
好的,您可以使用Java中的JSON库解析JSON字符串,然后获取到students数组对应的JSONArray对象,再遍历JSONArray中的每个元素,将其转换为JSONObject对象。最后可以打印出每个JSONObject对象对应的Java对象,代码实现如下:
```java
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonString = "{ \"class\": \"1A\", \"teacher\": \"Mr. Smith\", \"students\": [ { \"name\": \"Alice\", \"age\": 12, \"gender\": \"female\" }, { \"name\": \"Bob\", \"age\": 13, \"gender\": \"male\" } ] }";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray studentsArray = jsonObject.getJSONArray("students");
for (int i = 0; i < studentsArray.length(); i++) {
JSONObject studentObject = studentsArray.getJSONObject(i);
String name = studentObject.getString("name");
int age = studentObject.getInt("age");
String gender = studentObject.getString("gender");
Student student = new Student(name, age, gender);
System.out.println(student);
}
}
}
class Student {
private String name;
private int age;
private String gender;
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
```
运行结果如下:
```
Student{name='Alice', age=12, gender='female'}
Student{name='Bob', age=13, gender='male'}
```
其中,Student类是自定义的Java类,用于存储每个学生的信息。在遍历JSONArray对象时,可以通过调用getXXX()方法获取JSONObject对象中的属性值,并根据这些属性值创建新的Java对象。
阅读全文