{
"name": "三班",
"students": [
{
"age": 25,
"gender": "female",
"grades": "三班",
"name": "露西",
"score": {
"网络协议": 98,
"JavaEE": 92,
"计算机基础": 93
},
"weight": 51.3
},
{
"age": 26,
"gender": "male",
"grades": "三班",
"name": "杰克",
"score": {
"网络安全": 75,
"Linux操作系统": 81,
"计算机基础": 92
},
"weight": 66.5
},
{
"age": 25,
"gender": "female",
"grades": "三班",
"name": "莉莉",
"score": {
"网络安全": 95,
"Linux操作系统": 98,
"SQL数据库": 88,
"数据结构": 89
},
"weight": 55
}
]
}
我们来解析一下这个Json字符串。
首先, 最外层由一个大括弧”{}”包裹,那么我们对应的可以建一个实体类来对应,内部有两个元素,元素name比较明显是字符串类型的,元素students的值是由一个中括弧”[]”包裹,那么它对应的应该是一个数组或者列表。
接下来, 我们分析一下中括弧”[]”内部内容格式,中括弧内有三个大括弧包裹着的内容,并且内容格式基本相同,那么我们可以再定义一个实体类来对应这些大括弧。但是我们发现三个大括弧中的内容还是有些区别的,元素score对应的值虽然都是由一个大括弧来包裹,但是里边key的名称和数量都不相同。这样的情况我们不能很好的定义一个实体类来对应这个大括弧内的内容,不过我们可以定义一个Map来对应这个大括弧内的内容。
最终, 定义出来的实体类如下。
Grades.Java
package com.bean;
import java.util.List;
public class Grades {
private String name;//班级名称
private List<Student> students;//班里的所有学生
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
Student.java
package com.bean;
import java.util.Map;
/**
* 学生
*/
public class Student {
private int age;//年龄
private String gender;//性别,male/female
private String grades;//班级
private String name;//姓名
private Map<String, Integer> score;//各科分数
private float weight;//体重
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGrades() {
return grades;
}
public void setGrades(String grades) {
this.grades = grades;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Integer> getScore() {
return score;
}
public void setScore(Map<String, Integer> score) {
this.score = score;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
}
定义完之后,解析过程就非常简单了:
package com.test;
import net.sf.json.JSONObject;
import com.bean.Grades;
public class Domain {
public static void main(String[] args) {
String jsonStr = "{"name":"三班","students":[{"age":25,"gender":"female","grades":"三班","name":"露西","score":{"网络协议":98,"JavaEE":92,"计算机基础":93},"weight":51.3},{"age":26,"gender":"male","grades":"三班","name":"杰克","score":{"网络安全":75,"Linux操作系统":81,"计算机基础":92},"weight":66.5},{"age":25,"gender":"female","grades":"三班","name":"莉莉","score":{"网络安全":95,"Linux操作系统":98,"SQL数据库":88,"数据结构":89},"weight":55}]}";
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
Grades grades = (Grades) JSONObject.toBean(jsonObject, Grades.class);
}
}
这个Json字符串有多层嵌套,还有不固定的元素。只要学会了方法,不管多少层也是能分析出来的。