7.31 序列化 json

将json文件转为Swfit文件

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let path = "[https://gitshell.com/wcrane/FM-Res/raw/blob/master/channels.json](https://gitshell.com/wcrane/FM-Res/raw/blob/master/channels.json%22)"      //定义路径
        let url = NSURL(string: path)    //转化为url
        
        let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
            guard error == nil else {
                print("连接错误: \(error?.localizedDescription)")
                return
            }
            
            if let httpResponse = response as? NSHTTPURLResponse {
                if httpResponse.statusCode == 200 {
                    if let d = data {
                        let array = try! NSJSONSerialization.JSONObjectWithData(d, options: .AllowFragments) as? NSArray
                        
                        for dict in array! {
                            print(dict["channel_name"]!!)    //打印频道名字
                        }
                    }
                }
            }
        }
        task.resume()
        
        let jsonStr = "{\"name\":\"Zhangsan\"}"
        //将字符串转换为NSData
        let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding)
        let jsonObj = try! NSJSONSerialization.JSONObjectWithData(jsonData!, options: .AllowFragments)
        print(jsonObj["name"])
    }

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

你可能感兴趣的:(7.31 序列化 json)