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

Json的解析

时间:2015-06-16 09:21:01      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:json

json文本如下:

{
    "name": "百度",
    "url": "http://www.baidu.com",
    "address": {
        "street": "中关村",
        "city": "北京",
        "country": "中国"
    },
    "links": [
        {
            "name": "Google",
            "url": "http://www.google.com"
        },
        {
            "name": "Baidu",
            "url": "http://www.baidu.com"
        },
        {
            "name": "SoSo",
            "url": "http://www.SoSo.com"
        }
    ]
}

示例代码:

String json = "{\"name\":\"百度\",\"url\":\"http://www.baidu.com\"," +
                "\"address\":" +
                "{\"street\":\"中关村\",\"city\":\"北京\",\"country\":\"中国\"}," +
                "\"links\":" +
                "[{\"name\":\"Google\",\"url\":\"http://www.google.com\"}," +
                "{\"name\":\"Baidu\",\"url\":\"http://www.baidu.com\"}," +
                "{\"name\":\"SoSo\",\"url\":\"http://www.SoSo.com\"}]}";

        try {
            //取得整个Json对象
            JSONObject jsonObject = new JSONObject(json);
            String name = jsonObject.getString("name");
            System.out.println("name:"+name);
            String url = jsonObject.getString("url");
            System.out.println("url:"+url);
            //取得address对象
            JSONObject addressObject = jsonObject.getJSONObject("address");
            String street = addressObject.getString("street");
            System.out.println("street:"+street);
            String city = addressObject.getString("city");
            System.out.println("city:"+city);
            String country = addressObject.getString("country");
            System.out.println("country:"+country);
            //取得links数组
            JSONArray links = jsonObject.getJSONArray("links");
            for (int i = 0; i < links.length(); i++) {
                JSONObject linkObject = links.getJSONObject(i);
                System.out.println("*************"+i+"************");
                String LName = linkObject.getString("name");
                System.out.println("LName:"+LName);
                String lUrl = linkObject.getString("url");
                System.out.println("lUrl:"+lUrl);
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

运行结果:

name:百度
url:http://www.baidu.com
street:中关村
city:北京
country:中国
*************0************
LName:Google
lUrl:http://www.google.com
*************1************
LName:Baidu
lUrl:http://www.baidu.com
*************2************
LName:SoSo
lUrl:http://www.SoSo.com

其中使用了org.json.jar这个库,下载地址:http://download.csdn.net/detail/tuu_zed/8780297

Json的解析

标签:json

原文地址:http://blog.csdn.net/tuu_zed/article/details/46513659

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