ios swift http json

json解析测试:http://www.douban.com/j/app/radio/channels

 func get_data_from_url(url:String)

    {

        let httpMethod = "GET"

        let timeout = 15

        let url = NSURL(string: url)

        

        let urlRequest = NSMutableURLRequest(URL: url,

            cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,

            timeoutInterval: 15.0)

        let queue = NSOperationQueue()

        

        NSURLConnection.sendAsynchronousRequest(

            urlRequest,

            queue: queue,

            completionHandler: {(response: NSURLResponse!,

                data: NSData!,

                error: NSError!) in

                if data.length > 0 && error == nil{

                    

                    let json = NSString(data: data, encoding: NSASCIIStringEncoding)

                   // let enc = CFStringConvertEncodingToNSStringEncoding(0x0632)

                    

                  // let json  = NSString( data: data,  encoding:enc)

                    

                  //  encoding:gbkEncoding

                    

                    //  let json = NSString(data: data, encoding: NSUTF8StringEncoding)

                    

                    //self.extract_json(json)

                    println(json)

                    // self.praseJson(data)

                }else if data.length == 0 && error == nil{

                    println("Nothing was downloaded")

                } else if error != nil{

                    println("Error happened = \(error)")

                }

            }

        )

    }
func praseJson(data: NSData) {

        var json: AnyObject = NSJSONSerialization.JSONObjectWithData(data,options:NSJSONReadingOptions.AllowFragments,error:nil)!

        var weatherInfos: AnyObject = json.objectForKey("channels")! //json结构字段名。

        //var city:AnyObject = weatherInfo.objectForKey("name")!

        // json 数组

        

        for result in weatherInfos as NSArray {

            var name = result.objectForKey("name") as NSString

            println(name)

        }

        

//        println(weatherInfo)

    }

 

你可能感兴趣的:(swift)