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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值