使用Map List 封装json数据
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>
import net.sf.json.JSONObject;
public static void main(String[] args) { // 使用Map List 封装json数据 // 例子: 教室 有一张讲桌,一块黑板,30个学生, //{"讲桌":"讲桌A","黑板":"黑板A","全体同学":[{"学生":"小明"},{"学生":"小红"}]} Map<String,Object> classroom = new HashMap<String,Object>(); classroom.put("desk", "讲桌A"); classroom.put("blackboard", "黑板A"); List<Map<String,Object>> students = new ArrayList<Map<String,Object>>(); Map<String,Object> student1 = new HashMap<String,Object>(); student1.put("student", "小明"); students.add(student1); Map<String,Object> student2 = new HashMap<String,Object>(); student2.put("student", "小红"); students.add(student2); classroom.put("students", students); System.out.println(JSONObject.fromMap(classroom).toString()); //Console: //{"students":[{"student":"小明"},{"student":"小红"}],"blackboard":"黑板A","desk":"讲桌A"} JSONObject jo = JSONObject.fromMap(classroom); System.out.println(jo.get("desk")); //Console: //讲桌A System.out.println(jo.get("blackboard")); //Console: //黑板A Iterator<JSONObject> student = jo.getJSONArray("students").iterator(); while(student.hasNext()){ System.out.println(student.next().get("student")); //Console: //小明 //小红 } }