7.31 json2
新建一个类 ChannelModel
import Foundation
class ChannelModel {
var channel_id: String! //定义成员变量
var channel_name: String!
var coverUrl: NSURL!
init(dict: NSDictionary) { //写一个构造函数,把dict定义为字典类型
if let chId = dict["channel_id"] {
channel_id = chId as! String
}
if let chName = dict["channel_name"] {
channel_name = chName as! String
}
if let cUrl = dict["coverUrl"] {
coverUrl = NSURL(string: cUrl as! String)
}
}
}
回到view control界面:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let path = "https://gitshell.com/wcrane/FM-Res/raw/blob/master/channels.json"
let url = NSURL(string: path)
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 //NSDictionary
for dict in array! {
// //1. 不会提示
// //2. 类型不明确
//
// //用数据模型对象
// //1. 提示
// //2. 类型确定
// //3. 可以对数据进行初步处理
let ch = ChannelModel(dict: dict as! NSDictionary)
//调用一开始写的ChannelModel函数
print(ch.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"])
//Swift -> JSON
let dict1 = ["中文", "日文", "英文"]
//由第二个参数决定是否需要空格、换行之类格式化字符
let data1 = try! NSJSONSerialization.dataWithJSONObject(dict1, options: [])
let jsonStr1 = NSString(data: data1, encoding: NSUTF8StringEncoding)
print(jsonStr1!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}