Swift2.0天气预报小实例 - 解析JSON数据内置NSJSONSerialization与第三方JSONKit

import UIKit

class ViewController: UIViewController {

    @IBOutlet var labelWeather: UITextView!
    @IBAction func loadWeather(sender: AnyObject) {
// loadWeather2()
        testJson()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
        //testJson()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // dispose of any resources that can be recreated.
    }

    func loadWeather2(){
        do{
            //通过天气预报API获取json数据
            let url = NSURL(string: "http://www.weather.com.cn/adat/sk/101100501.html")
            let data = try NSData(contentsOfURL: url!,options: NSDataReadingOptions())

            //NSData转换成Nsstring打印输出
// let str = Nsstring(data:data,encoding: NSUTF8StringEncoding)
// print(str)

            //把NSData对象转换回JSON对象
            let json : AnyObject! = try NSJSONSerialization.JSONObjectWithData(data,options:NSJSONReadingOptions.AllowFragments)
            //解析JSON数据
            let weatherinfo :AnyObject = json.objectForKey("weatherinfo")!
            let city : AnyObject  = weatherinfo.objectForKey("city")! //城市
            let wd : AnyObject = weatherinfo.objectForKey("WD")!   //风向
            let ws : AnyObject = weatherinfo.objectForKey("WS")!   //风级
            let temp : AnyObject = weatherinfo.objectForKey("temp")! //温度
            //获取
            labelWeather.text = "城市:\(city)\n温度:\(temp)\n风向:\(wd)\n风速:\(ws)"
        }catch{
            print(error)
        }
    }
    //使用第三方库 - JSONKit
    func testJson(){
        do{
            let url = NSURL(string: "http://www.weather.com.cn/adat/sk/101100501.html")
            let user = try NSData(contentsOfURL: url!,options: NSDataReadingOptions())
            //由NSData 反解析回为字典
            let dic = user.objectFromJSONData() as! NSDictionary
            let weatherinfo :AnyObject = dic.objectForKey("weatherinfo")!
            let city : AnyObject  = weatherinfo.objectForKey("city")! //城市
            let wd : AnyObject = weatherinfo.objectForKey("WD")!   //风向
            let ws : AnyObject = weatherinfo.objectForKey("WS")!   //风级
            let temp : AnyObject = weatherinfo.objectForKey("temp")! //温度
            labelWeather.text = "城市:\(city)\n温度:\(temp)\n风向:\(wd)\n风速:\(ws)"
        }catch{
            print(error)
        }
    }

}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...