Swift 解析 JSON

/**

     *  顯示數據

     */

    

    

    /**

     *   一,使用自帶的NSJSONSerialization

     蘋果從IOS5.0後推出了SDK自帶的JSON解決方案NSJSONSerialization,這是一個非常好用的JSON生成和解析工具,效率也比其他第三方開源項目高。

     

     NSJSONSerialization能將JSON轉換成Foundation對象,也能將Foundation對象轉換成JSON,但轉換成JSON的對象必須具有如下屬性:

     1,頂層對象必須是NSArray或者NSDictionary

     2,所有的對象必須是NSStringNSNumberNSArrayNSDictionaryNSNull的實例

     3,所有NSDictionarykey必須是NSString類型

     4,數字對象不能是非數值或無窮

     注意:儘量使用NSJSONSerialization.isValidJSONObject先判斷能否轉換成功

     

    */


    //聲明:result是網絡請求下來的數據

    func loadData(result:NSDictionary) {

//在進行網絡解析時,由於剛正式的用swift寫項目,遇到各種問題,各種嘗試,終於找到破解方法,下面我將進行網絡請求時遇到的問題與大家分享交流下(ps:swift語法特點與OC差異很大,接觸swift時也許不太習慣)    

            //下面這行代碼這麼寫 會報錯:如下 cannot convert value of type 'AnyObject' to specified type 'NSDictionary'

            //let data:NSDictionary = result1 .objectForKey("data")

            

            //下面這行代碼這麼寫 會報錯:如下 fatal error: unexpectedly found nil while unwrapping an Optional value

            //let data = result1.valueForKey("data") as! [NSDictionary:AnyObject]

            

            //下面這行代碼這麼寫 會報錯:如下 Could not cast value of type '__NSCFArray' (0x19eba9150) to 'NSDictionary' (0x19eba9380).

            //let yourFirstObj : NSDictionary =  result["productList"] as! NSDictionary

//上面是我遇到的問題,大家一定要注意下

        print(result)

        //首先判斷能不能轉換

        if (!NSJSONSerialization.isValidJSONObject(result)) {

            print("is not a valid json object")

            return

        }else {

            // *****

            //     樣例1:將對象轉成json字符串,再轉回來

            // ****

            

            //利用OCjson庫轉換成OCNSData

            //如果設置optionsNSJSONWritingOptions.PrettyPrinted,則打印格式更好閱讀

            let data : NSData! = try? NSJSONSerialization.dataWithJSONObject(result, options: [])

            // ---------------下面4行代碼時解析 《 json字符串 》--------------------

            //NSData轉換成NSString打印輸出<解析json字符串>

            let str = NSString(data:data, encoding: NSUTF8StringEncoding)

            //輸出json字符串

            print("Json Str:");

            print(str)

            self.loadDataByStrOfLikeJson(str! as String) //<解析json字符串>

            //----------------上面4行代碼時解析 《 json字符串 》---------------------

    //NSData對象轉換回JSON對象

            let json : AnyObject! = try? NSJSONSerialization

                .JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments)

            print("Json Object:");

            print(json)

            

            //驗證JSON對象可用性

            let dataList:AnyObject = json.objectForKey("data")!//dataList數據

            print("dataList: \(dataList)")


            

            let banners:AnyObject = dataList.objectForKey("banners")!//banner圖數據

            print("banners: \(banners)")


            let icons:AnyObject = dataList.objectForKey("icons")!//icons圖數據

            print("icons: \(icons)")


            let notice:AnyObject = dataList.objectForKey("notice")!//notice 公告

            print("notice: \(notice)")


            let productList:AnyObject = dataList.objectForKey("productList")!//cell列表

            print("productList: \(productList)")


            

        }



        

    }

    

    

    /** 

     *  樣例2:解析json字符串(由於是字符串內容是json數組,則轉成NSArray。如果字符串是json對象,則轉成NSDictionary。)

     */

    func  loadDataByStrOfLikeJson (str:String) {

    

        let data = str.dataUsingEncoding(NSUTF8StringEncoding)

        //NSData對象轉換回JSON對象

        let json : AnyObject! = try? NSJSONSerialization

            .JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments)

        print("Json Object:");

        print(json)

        

        /** json 數組

            let jsonArr = try! NSJSONSerialization.JSONObjectWithData(data!,

            options: NSJSONReadingOptions.MutableContainers) as! NSArray

            print("記錄數:\(jsonArr.count)")

            for json in jsonArr {

            print("ID", json.objectForKey("ID")!, "    Name", json.objectForKey("Name")!)

        }

        */

      

    }

//下面是我解析的json數據,僅供大家參考


{
    data =     {
        bankNorm = "https://www.zhuofanbaobei.com/wgtz/wap/product/bankNorm_ll.jsp";
        bankSafeUrlMobile = "http://www.zhuofanbaobei.com/activity/bymWap/html/safe/index.html";
        banners =         (
                        {
                description = "\U5927\U5e08\U5085 ";
                hdUrl = "<null>";
                id = 114;
                imgURL = "https://www.zhuofanbaobei.com/Images/mobile_img/banner/5ea58a20-1109-498c-987e-4efecae6a5ad.jpeg";
                insertTime = 1464675179000;
                isChange = 0;
                notice = "<null>";
                noticeId = "<null>";
                noticeUrl = www;
                pt = "\U624b\U673a";
                status = 0;
                title = "\U65af\U8482\U82ac";
                type = 1;
            },
                        {
                description = " ";
                hdUrl = "<null>";
                id = 112;
                imgURL = "https://www.zhuofanbaobei.com/Images/mobile_img/banner/ee912781-5568-470d-a3fd-a21e0909dd1b.png";
                insertTime = 1462258990000;
                isChange = 1;
                notice = "<null>";
                noticeId = "<null>";
                noticeUrl = "http://www.zhuofanbaobei.com/activity/bymWap/html/znqGame/index.html";
                pt = "\U624b\U673a";
                status = 0;
                title = "\U5468\U5e74\U5e860503";
                type = 1;
            },
                        {
                description = "\U4f70\U4ebf\U732b";
                hdUrl = "<null>";
                id = 100;
                imgURL = "https://www.zhuofanbaobei.com/Images/mobile_img/banner/73a6d4cf-2e2e-4148-9b7d-4451cb0152e5.jpeg";
                insertTime = 1461908762000;
                isChange = 0;
                notice = "<null>";
                noticeId = "<null>";
                noticeUrl = "http://www.zhuofanbaobei.com/activity/constrat/index2.html";
                pt = "\U624b\U673a";
                status = 0;
                title = "\U4f70\U4ebf\U732b";
                type = 1;
            },
                        {
                description = "\U4e03\U9f99\U73e0 ";
                hdUrl = "<null>";
                id = 98;
                imgURL = "https://www.zhuofanbaobei.com/Images/mobile_img/banner/010e2ae7-f1a6-46f3-8f60-f6788781efff.png";
                insertTime = 1461811364000;
                isChange = 0;
                notice = "<null>";
                noticeId = "<null>";
                noticeUrl = "www.baidu.com";
                pt = "\U624b\U673a";
                status = 0;
                title = "\U4e03\U9f99\U73e0";
                type = 1;
            },
                        {
                description = " ";
                hdUrl = "<null>";
                id = 96;
                imgURL = "https://www.zhuofanbaobei.com/Images/mobile_img/banner/d5a187e1-6e79-4170-ae40-8cb5c94a9abd.jpeg";
                insertTime = 1461140925000;
                isChange = 0;
                notice = "<null>";
                noticeId = "<null>";
                noticeUrl = "http://www.zhuofanbaobei.com/wgtz/Product/index!loadProduct.action";
                pt = "\U624b\U673a";
                status = 0;
                title = "banner\U6d4b\U8bd5001";
                type = 1;
            },
                        {
                description = "\U52a0\U7fa4 ";
                hdUrl = "<null>";
                id = 59;
                imgURL = "https://www.zhuofanbaobei.com/Images/mobile_img/banner/9e9e8a7a-8c7f-466f-ba67-e1d12ec21f22.jpeg";
                insertTime = 1447399494000;
                isChange = 0;
                notice = "<null>";
                noticeId = "<null>";
                noticeUrl = "http://jq.qq.com/?_wv=1027&k=XZtUb1";
                pt = "\U624b\U673a";
                status = 0;
                title = "\U52a0\U7fa4";
                type = 1;
            },
                        {
                description = " ";
                hdUrl = "<null>";
                id = 44;
                imgURL = "https://www.zhuofanbaobei.com/Images/mobile_img/banner/29112da5-dd78-4c5b-b170-66a399225714.jpeg";
                insertTime = 1443592940000;
                isChange = 0;
                notice = "<null>";
                noticeId = "<null>";
                noticeUrl = "http://m.zhuofanbaobei.com/baiyimaoWap/wap/product/hd_pic.jsp?picName=hd_lqb.jpg";
                pt = "\U624b\U673a";
                status = 0;
                title = "\U96f6\U94b1\U5305";
                type = 1;
            },
                        {
                description = " ";
                hdUrl = "<null>";
                id = 28;
                imgURL = "https://www.zhuofanbaobei.com/Images/mobile_img/banner/9b6936c1-9c8a-45e1-bd18-0903e8a2993b.jpeg";
                insertTime = 1440493714000;
                isChange = 0;
                notice = "<null>";
                noticeId = "<null>";
                noticeUrl = "http://m.zhuofanbaobei.com/baiyimaoWap/wap/product/qmlc.jsp?type=1";
                pt = "\U624b\U673a";
                status = 0;
                title = "\U5168\U6c11\U7406\U8d22\U6700\U7ec8\U7248";
                type = 1;
            },
                        {
                description = " ";
                hdUrl = "<null>";
                id = 15;
                imgURL = "https://www.zhuofanbaobei.com/Images/mobile_img/banner/406e1d2b-f53c-4562-acef-ec008d4b2426.jpeg";
                insertTime = 1439288590000;
                isChange = 0;
                notice = "<null>";
                noticeId = "<null>";
                noticeUrl = "https://www.zhuofanbaobei.com/wgtz/Product/indexNotice!getMobileNoticeById.action?type=1&noticeId=8ae98fe04f1a40bb014f1b1f55030008";
                pt = "\U624b\U673a";
                status = 0;
                title = "\U80fd\U6e90\U878d\U8d44";
                type = 1;
            }
        );
        direction =         {
            deirectionRelevant = "\U76f8\U5173\U56fe\U7247";
            directionProductDescription = "\U4ea7\U54c1\U8bf4\U660e";
            directionTargetDescription = "\U9879\U76ee\U8bf4\U660e";
            id = 1;
            insertTime = 1461055933000;
            note = "<null>";
            sourceVcbauhiniaSecurity = "\U8d44\U91d1\U4fdd\U969c";
            sourceVcpayment = "\U8fd8\U6b3e\U6765\U6e90";
            type = 0;
        };
        freshUrl = "http://www.zhuofanbaobei.com/activity/bymWap/html/newer/index.html";
        icons =         (
                        {
                iconKey = qd;
                iconName = "\U7b7e\U5230";
                iconUrl = "http://admin.baiyimao.com/Images/atc_img/1_qd3.png";
                id = 1;
                insertTime = 1459939747000;
                note = "";
                status = 0;
                type = 3;
            },
                        {
                iconKey = yqhy;
                iconName = "\U9080\U8bf7\U597d\U53cb";
                iconUrl = "http://admin.baiyimao.com/Images/atc_img/2_yqhy3.png";
                id = 2;
                insertTime = 1459940088000;
                note = "<null>";
                status = 0;
                type = 3;
            },
                        {
                iconKey = msc;
                iconName = "\U55b5\U5546\U57ce";
                iconUrl = "http://admin.baiyimao.com/Images/atc_img/3_msc3.png";
                id = 3;
                insertTime = 1459940246000;
                note = "<null>";
                status = 0;
                type = 3;
            },
                        {
                iconKey = hdzx;
                iconName = "\U6d3b\U52a8\U4e2d\U5fc3";
                iconUrl = "http://admin.baiyimao.com/Images/atc_img/4_hdzx3.png";
                id = 4;
                insertTime = 1459940246000;
                note = "<null>";
                status = 0;
                type = 3;
            },
                        {
                iconKey = sxzq;
                iconName = "\U65b0\U624b\U4e13\U533a";
                iconUrl = "http://admin.baiyimao.com/Images/atc_img/5_xszq3.png";
                id = 5;
                insertTime = 1459940246000;
                note = "<null>";
                status = 0;
                type = 3;
            },
                        {
                iconKey = bzzx;
                iconName = "\U5e2e\U52a9\U4e2d\U5fc3";
                iconUrl = "http://admin.baiyimao.com/Images/atc_img/6_bzzx3.png";
                id = 6;
                insertTime = 1459940246000;
                note = "<null>";
                status = 0;
                type = 3;
            }
        );
        inviteBackgroundUrl = "http://admin.baiyimao.com/Images/atc_img/hd_pic.jsp?picName=share_app.png";
        notice =         {
            description = "<p>
\n\t\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b
\n</p>
\n<p>
\n\t\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b
\n</p>
\n<p>
\n\t\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b
\n</p>";
            endTime = 1465747200000;
            id = 8a0bb08255424609015542ab45f7000a;
            index = 1;
            insertTime = 1465702368000;
            noticeUrl = "https://www.zhuofanbaobei.com/wgtz/Product/indexNotice!getMobileNoticeById.action?type=1&noticeId=8a0bb08255424609015542ab45f7000a";
            status = 0;
            title = "\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b\U7cfb\U7edf\U6d88\U606f\U6d4b\U8bd5\U4e00\U4e0b";
            titleUrl = "https://www.zhuofanbaobei.com/Images/web_img/notice/slt/293d86b4-bcf0-48ff-ad2e-98fb78d5ecc3.jpeg";
            type = 3;
        };
        productList =         (
                        {
                annualEarnings = 15;
                atleastMoney = 10000;
                cgcpType = "<null>";
                id = 8a0bb0825551b92b015552923041001a;
                index = 0;
                label = "\U6d4b\U8bd5";
                lcqx = 10;
                productStatus = 0;
                productType = 1;
                title = "\U6d4b\U8bd5\U65b0\U624b1";
                tzqx = 10;
                wcjd = 0;
            },
                        {
                annualEarnings = "6.5";
                atleastMoney = 20000;
                cgcpType = 1;
                id = 8a0bb082554d08b5015551b6ddb40064;
                index = 1;
                label = "\U6d4b\U8bd5\U6d4b\U8bd5,\U6d4b\U8bd5\U63a8\U8350";
                lcqx = 20;
                productStatus = 0;
                productType = 0;
                title = "\U63a8\U8350";
                tzqx = 19;
                wcjd = 0;
            },
                        {
                annualEarnings = 10;
                atleastMoney = 10000;
                cgcpType = 2;
                id = 8a0bb0825551b92b015552321d100015;
                index = 2;
                label = "\U7231\U7684\U8272\U653e";
                lcqx = 20;
                productStatus = 1;
                productType = 0;
                title = "\U5e38\U89c4\U4e0d\U53ef\U4f7f\U7528";
                tzqx = 20;
                wcjd = 1;
            }
        );
        riskControlUrl = "http://m.zhuofanbaobei.com/baiyimaoWap/Product/recommend/fengkong.jsp";
        signUrl = "http://www.zhuofanbaobei.com/activity/bymWap/html/sign/index.html";
        "zrgz_url_common" = "http://m.zhuofanbaobei.com/baiyimaoWap/Product/product/zrgz_common.jsp?type=1";
    };
    end = ok;
    message = "\U83b7\U53d6\U9996\U9875\U6570\U636e\U6210\U529f";
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章