首页 > Web开发 > 详细

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

时间:2017-09-27 13:59:26      阅读:258      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!