JSONObject 对于放入的object,最终生成的json是什么样的?
两个JavaBean:
public class ClassBean {
private int grade;
private String className;
private boolean isExperimentalClass;
private List students;
//······
}
public class StudentBean {
private String stuName;
private int sno;
private Map scores;
private List hobby;
//·······
}
对于javeBean 生成JSON
public class JsonTest {
public static void main(String[] args) {
ClassBean classBean = new ClassBean();
List stus = new ArrayList();
StudentBean stu1 = new StudentBean();
stu1.setSno(110701);
stu1.setStuName("JIM");
Map scores = new HashMap();
scores.put("math", 95);
scores.put("chinese", 95);
scores.put("english", 92);
stu1.setScores(scores);
List hobby1 = new ArrayList();
hobby1.add("run");
hobby1.add("eat");
hobby1.add("sleep");
stu1.setHobby(hobby1);
stus.add(stu1);
StudentBean stu2 = new StudentBean();
stu2.setSno(110702);
stu2.setStuName("KIM");
Map scores2 = new HashMap();
scores2.put("math", 98);
scores2.put("chinese", 96);
scores2.put("english", 92);
stu2.setScores(scores2);
List hobby2 = new ArrayList();
hobby2.add("read");
hobby2.add("play");
stu2.setHobby(hobby2);
stus.add(stu2);
classBean.setClassName("二班");
classBean.setExperimentalClass(false);
classBean.setGrade(1);
classBean.setStudents(stus);
JSONObject jobj = new JSONObject();
jobj.put("class", classBean);
System.out.println(jobj.toString());
}
}
输出的结果:
{
"class": {
"className": "二班",
"experimentalClass": false,
"grade": 1,
"students": [
{
"hobby": [
"run",
"eat",
"sleep"
],
"scores": {
"math": 95,
"english": 92,
"chinese": 95
},
"sno": 110701,
"stuName": "JIM"
},
{
"hobby": [
"read",
"play"
],
"scores": {
"math": 98,
"english": 92,
"chinese": 96
},
"sno": 110702,
"stuName": "KIM"
}
]
}
}