<p>Json示例:</p><pre class="brush:java;toolbar:false">[
{
"age":25,
"gender":"female",
"grades":"三班",
"name":"露西",
"weight":51.3
},
{
"age":26,
"gender":"male",
"grades":"三班",
"name":"杰克",
"weight":66.5
},
{
"age":25,
"gender":"female",
"grades":"三班",
"name":"莉莉",
"weight":55
}
]</pre><p>我们来解析一下这个Json字符串。</p><p>首先,因为此Json字符串最外边是由一个中括弧"[]"包裹,那么,最终我们会用数组或者列表来接收它。</p><p>接下来,我们能看到中括弧里边有三个同级的大括弧,并且每个大括弧里包含的内容是相同的,大括弧我们可以对应创建一个类,我们创建一个类Student.java,并对应大括弧内的元素,定义相应的成员变量,生成get/set方法。</p><p>我们生成的Student.java如下:</p><pre class="brush:java;toolbar:false">packagecom.bean;
/**
*学生
*/
publicclassStudent{
privateintage;//年龄
privateStringgender;//性别,male/female
privateStringgrades;//班级
privateStringname;//姓名
privatefloatweight;//体重
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
publicStringgetGender(){
returngender;
}
publicvoidsetGender(Stringgender){
this.gender=gender;
}
publicStringgetGrades(){
returngrades;
}
publicvoidsetGrades(Stringgrades){
this.grades=grades;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicfloatgetWeight(){
returnweight;
}
publicvoidsetWeight(floatweight){
this.weight=weight;
}
}</pre><p>解析成数组或列表:</p><pre class="brush:java;toolbar:false">packagecom.test;
importjava.util.ArrayList;
importjava.util.List;
importnet.sf.json.JSONArray;
importcom.bean.Student;
publicclassDomain{
@SuppressWarnings("unchecked")
publicstaticvoidmain(String[]args){
StringjsonStr="[{\"age\":25,\"gender\":\"female\",\"grades\":\"三班\",\"name\":\"露西\",\"weight\":51.3},{\"age\":26,\"gender\":\"male\",\"grades\":\"三班\",\"name\":\"杰克\",\"weight\":66.5},{\"age\":25,\"gender\":\"female\",\"grades\":\"三班\",\"name\":\"莉莉\",\"weight\":55}]";
JSONArrayjsonArray=JSONArray.fromObject(jsonStr);
Student[]stus=newStudent[3];
List<Student>list=newArrayList<Student>();
stus=(Student[])JSONArray.toArray(jsonArray,Student.class);//转换成数组
list=(List<Student>)JSONArray.toCollection(jsonArray,Student.class);//转换成列表
}
}</pre><p>通过数组或者列表生成Json字符串:</p><pre class="brush:as3;toolbar:false">packagecom.test;
importjava.util.ArrayList;
importjava.util.List;
importnet.sf.json.JSONArray;
importcom.bean.Student;
publicclassDomain{
@SuppressWarnings("unchecked")
publicstaticvoidmain(String[]args){
Studentstu1=newStudent();
Studentstu2=newStudent();
Studentstu3=newStudent();
stu1.setAge(25);
stu1.setGender("female");
stu1.setGrades("三班");
stu1.setName("露西");
stu1.setWeight(51.3f);
stu2.setAge(26);
stu2.setGender("male");
stu2.setGrades("三班");
stu2.setName("杰克");
stu2.setWeight(66.5f);
stu3.setAge(25);
stu3.setGender("female");
stu3.setGrades("三班");
stu3.setName("莉莉");
stu3.setWeight(55.0f);
Student[]stus=newStudent[3];
List<Student>list=newArrayList<Student>();
stus[0]=stu1;
stus[1]=stu2;
stus[2]=stu3;
list.add(stu1);
list.add(stu2);
list.add(stu3);
StringjsonStr1=JSONArray.fromObject(stus).toString();
StringjsonStr2=JSONArray.fromObject(list).toString();
System.out.println(jsonStr1);
System.out.println(jsonStr2);
}
}</pre>