1.需要阿里巴巴的fastjson.jar
2.将json字符串转为JSONObject,通过JSONObject.parseObject(json字符串),取值的话通过json对象的getString(),getIntValue()等等获取JSONObject的值
String student = "{‘name‘:‘张三‘,‘age‘:30}" ;
JSONObject json = JSONObject.parseObject(student) ;
System.out.println("----------"+json.toString());
System.out.println("----------"+json.getString("name"));
System.out.println("----------"+json.getIntValue("age"));
结果:
----------{"age":30,"name":"张三"}
----------张三
----------30
2.将json字符串转为JSONArray,通过JSONArray.parseArray(json字符串),取值通过循环读取,读取的每一条数据,对象是一个JSONObject,集合就是JSONArray,然后通过json对象的getString(),getIntValue()等等获取JSONObject的值
String stu = "[{‘name‘:‘张三‘,‘age‘:20},{‘name‘:‘李四‘,‘age‘:30}]" ;
JSONArray jsonArray = JSONArray.parseArray(stu) ;
for (Object o : jsonArray) {
JSONObject j = JSONObject.parseObject(o.toString()) ;
System.out.println("-----------"+j.getString("name"));
System.out.println("-----------"+j.getIntValue("age"));
}
结果:
-----------张三
-----------20
-----------李四
-----------30
3.将对象、集合转为json字符串用JSON.toJSONString() ;
Student s = new Student() ; s.setAge(20); s.setName("张三"); String sutdent = JSON.toJSONString(s) ; System.out.println("-----------"+sutdent); List<Student> students = new ArrayList<Student>() ; students.add(s) ; String j = JSON.toJSONString(students) ; System.out.println("--------------"+j); 结果: -----------{"age":20,"name":"张三"} --------------[{"age":20,"name":"张三"}]
json三-------com.alibaba.fastjson
原文:http://www.cnblogs.com/-scl/p/7601377.html