依赖的jar包
package nettest.json; public class Grade { private Student student; private String num; public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } }
package nettest.json; public class Student { private String name; private int age; private String[] hobby; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } }
package nettest.json; import java.util.HashMap; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonTestOne { public static void main(String[] args) { //JSONObject对象和Java对象的互相转换 toJsonJsonConfig(); toJson(); toJsonMap(); } public static JSONObject common(){ Grade newGrade = new Grade(); newGrade.setNum("One"); Student newStudent = new Student(); newStudent.setAge(2); newStudent.setName("Ziv"); newStudent.setHobby(new String[]{"篮球","足球"}); newGrade.setStudent(newStudent); JSONObject js = JSONObject.fromObject(newGrade); System.out.println(js.toString()); return js; } public static void toJsonJsonConfig(){ JSONObject js = common(); Object ob = js.toBean(js); } public static void toJson(){ JSONObject js = common(); Grade g = (Grade) js.toBean(js, Grade.class); System.out.println(g.getStudent().getName()); JSONObject map = (JSONObject) js.get("student"); JSONArray hobby = map.getJSONArray("hobby"); Student st = (Student) js.toBean(map, Student.class); System.out.println(st.getAge()); // JSONObject jsonObject = JSONObject.fromObject("{"num":"One","student":{"name":"Ziv","age":2,"hobby":["篮球","足球"]}}"); } public static void toJsonMap(){ JSONObject js = common(); Map conMap = new HashMap(); conMap.put("stu", Student.class); conMap.put("gra", Grade.class); Student st = (Student)JSONObject.toBean(js, Student.class, conMap); } }