json三-------com.alibaba.fastjson

1.需要阿里巴巴的fastjson.jar

下载地址:http://download.csdn.net/download/muyeju/9999520

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

3.将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
    

4.将对象、集合转为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":"张三"}]

 5.总结

  fastjson是阿里巴巴公司开发的一个高性能JSON处理器,FastJson采用独创的算法,将parse的速度提升到极致,超过所有json库,所以它的性能很好。

原文地址:https://www.cnblogs.com/-scl/p/7601377.html