码迷,mamicode.com
首页 > Web开发 > 详细

JSON数据解析

时间:2016-04-11 18:45:22      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

    String str ="{‘person‘:‘oneself‘,‘info‘:{‘name‘:‘小王‘,‘age‘:22},‘people‘:[{‘a‘:‘Brett‘,‘b‘:‘McLaughlin‘,‘c‘:‘aaaa‘},{‘a‘:‘Jason‘,‘b‘:‘Hunter‘,‘c‘:‘bbbb‘},{‘a‘:‘Elliotte‘,‘b‘:‘Harold‘,‘c‘:‘cccc‘}]}";
    JSONObject jsonObj = JSONObject.fromObject(str);
    String person = jsonObj.getString("person");
    System.out.println("获取字符person:"+person);
    
    JSONObject info = jsonObj.getJSONObject("info");
    System.out.println("获取对象info  :(name:"+info.getString("name")+"  age:"+info.getString("age")+")");
    System.out.println("获取数组people:");
    JSONArray arr = jsonObj.getJSONArray("people");
    for (int i = 0; i < arr.size(); i++) {
        JSONObject o = arr.getJSONObject(i);
        String a = (String) o.get("a");
        String b = (String) o.get("b");
        String c = (String) o.get("c");
        System.out.println(a+"|"+b+"|"+c);
    }
    
    //Ajax请求带参Json数据
    //var jsonArr = new Array();
    //var str = JSON.stringify(jsonArr);   ==》JSON数组转字符串(对象同理)
    String gradeString ="[{‘a‘:‘a1‘,‘b‘:‘b1‘,‘c‘:‘c1‘},{‘a‘:‘a2‘,‘b‘:‘b2‘,‘c‘:‘c2‘},{‘a‘:‘a3‘,‘b‘:‘b3‘,‘c‘:‘c3‘}]";
    JSONArray jsonArr = JSONArray.fromObject(gradeString); //此处为null,或者会直接报错
    System.out.println("解析Ajax请求传来的Json数组:");
    for (int i = 0; i < jsonArr.size(); i++) {
        JSONObject o = jsonArr.getJSONObject(i);
        String a = (String) o.get("a");
        String b = (String) o.get("b");
        String c = (String) o.get("c");
        System.out.println(a+"|"+b+"|"+c);
    }

 

JSON数据解析

标签:

原文地址:http://www.cnblogs.com/zhaojinhui/p/5379179.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!