json-lib 将list或者对象转化为json格式

下载:
    到http://json-lib.sourceforge.net下载json-lib-1.1-jdk15.jar,运行json还需要的包有:commons-lang.jar、commons-logging.jar,commons-beanutils.jar、xom-1.0-2005-01-05.jar、ezmorph-1.0.1.jar,可在http://www.docjar.com搜索下载。
1  示例说明:
    list -> json:
  Student[] stus = new Student[5]; 
                List<Student> stuList = new ArrayList<Student>(); 
                for (int i = 0; i < stus.length; i++) { 
                stus[i] = new Student(); 
                stus[i].setAge(i*10+8); 
                stus[i].setName("张三"+i); 
                stus[i].setSex("和"); 
                //添加到list,一会儿用 
                stuList.add(stus[i]); 
                } 
                JSONArray jsonArray = JSONArray.fromObject(stus); 
              System.out.println(jsonArray);

对象(Student)-->json:
  Student student = new Student();
          student.setAge(18);
          student.setName("zhangsan");
          student.setSex("male");
          JSONObject jsonObject = JSONObject.fromObject(student);
          System.out.println(jsonObject);

map+list   --> json:
   Student[] stus = new Student[5];
                List<Student> stuList = new ArrayList<Student>();
                for (int i = 0; i < stus.length; i++) {
                        stus[i] = new Student();
                        stus[i].setAge(i * 10 + 8);
                        stus[i].setName("张三" + i);
                        stus[i].setSex("和");
                        // 添加到list,一会儿用
                        stuList.add(stus[i]);
                }
               
                Map<String, Object> map = new HashMap<String, Object>();
                Teacher teacher = new Teacher();
                teacher.setAge(30);
                teacher.setName("laoshi");
                teacher.setSex("male");
                map.put("teacher", teacher);
                map.put("student", stuList);
                JSONObject jsonObjectFromMap = JSONObject.fromObject(map);
                System.out.println(jsonObjectFromMap);  

你可能感兴趣的:(json,.net)