1.需要引入的包
下载地址:http://download.csdn.net/download/muyeju/9999535
2.缺包会出现如下错误
1、org/apache/commons/lang/exception/NestableRuntimeException是缺少commons-lang-2.6.jar
2、net/sf/ezmorph/Morpher是缺少ezmorph-1.0.6.jar
3、org.apache.commons.logging.LogFactory是缺少
4、org.apache.commons.collections.map.MultiKeyMap是缺少commons-collections-3.2.1.jar
5、org.apache.commons.beanutils.DynaBean是缺少commons-beanutils-1.9.2.jar
3.将对象、Map转为json,用JSONObject.fromObject(对象)
Student s = new Student() ; s.setAge(20); s.setName("张三"); JSONObject json = JSONObject.fromObject(s) ; System.out.println("----------"+json.toString());
结果:----------{"age":20,"name":"张三"}
4.将集合转为json,用JSONArray.fromObject(集合)
List<Student> students = new ArrayList<Student>() ; students.add(s) ; JSONArray jsonArray = JSONArray.fromObject(students) ; System.out.println("----------"+jsonArray.toString()); 结果:----------[{"name":"张三","age":20}]
5.json对象数组转为集合,先把json对象数组字符串转为JSONArray,然后调用JSONArray对象的toList()方法
String student = "[{'name':'张三','age':20},{'name':'李四','age':21}]" ; JSONArray j = JSONArray.fromObject(student) ; List<Student> students = JSONArray.toList(j, Student.class) ; for (Student s : students) { System.out.println("-----------"+s.getName()); System.out.println("-----------"+s.getAge()); }
结果:
-----------张三
-----------20
-----------李四
-----------21
6.json字符串对象转为对象,先将字符串转为JSONObject,然后调用它的toBean()方法
String student = "{'name':'李四','age':21}" ; JSONObject jsonObject = JSONObject.fromObject(student) ; Student s = (Student) jsonObject.toBean(jsonObject, Student.class) ; System.out.println("--------"+s.getName()); System.out.println("--------"+s.getAge());
结果:
--------李四
--------21
7.缺点:
1、依赖的jar包太多,像fastjson,gosn这些就一个jar
2、如果要将json字符串转为Bean,且json里面有List或者Map,则,解析会报错,例如:String s = "{'name':'张三','age':20,'teacher':[{'name':'康','age':40,'subject':'语文'}]}" ;这种类型的json解析成对象就会报错,如果没有里面的teacher则不会报错