Json是一種輕量級(jí)的數(shù)據(jù)交換格式,它支持嵌套、數(shù)組和基本數(shù)據(jù)類(lèi)型。在Java中,我們可以使用Json解析庫(kù)來(lái)解析Json數(shù)據(jù),其中最常用的是Gson庫(kù)。下面通過(guò)一個(gè)例子來(lái)展示如何解析Json中的數(shù)組對(duì)象數(shù)組對(duì)象。
//Json數(shù)據(jù)格式 { "students": [ { "name": "Tom", "age": 18, "courses": [ { "courseName": "Math", "score": 90 }, { "courseName": "English", "score": 80 } ] }, { "name": "Lily", "age": 20, "courses": [ { "courseName": "Physics", "score": 85 }, { "courseName": "Computer Science", "score": 95 } ] } ] } //Student類(lèi) public class Student { private String name; private int age; private Listcourses; //getter and setter } //Course類(lèi) public class Course { private String courseName; private int score; //getter and setter } //解析Json Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(jsonStr, JsonObject.class); JsonArray studentArray = jsonObject.getAsJsonArray("students"); List studentList = new ArrayList<>(); for (JsonElement jsonElement : studentArray) { JsonObject studentObject = jsonElement.getAsJsonObject(); String name = studentObject.get("name").getAsString(); int age = studentObject.get("age").getAsInt(); JsonArray courseArray = studentObject.getAsJsonArray("courses"); List courseList = new ArrayList<>(); for (JsonElement courseElement : courseArray) { JsonObject courseObject = courseElement.getAsJsonObject(); String courseName = courseObject.get("courseName").getAsString(); int score = courseObject.get("score").getAsInt(); Course course = new Course(); course.setCourseName(courseName); course.setScore(score); courseList.add(course); } Student student = new Student(); student.setName(name); student.setAge(age); student.setCourses(courseList); studentList.add(student); }
在以上例子中,我們使用Gson庫(kù)來(lái)解析Json字符串。首先將Json字符串轉(zhuǎn)為JsonObject對(duì)象,然后通過(guò)getAsJsonArray方法獲取學(xué)生數(shù)組,遍歷數(shù)組得到每個(gè)學(xué)生的Json對(duì)象。根據(jù)Json對(duì)象的字段名和類(lèi)型,創(chuàng)建對(duì)應(yīng)的Java對(duì)象,將屬性值設(shè)置到對(duì)象中。最終得到List<Student>對(duì)象,包含所有學(xué)生的信息。