#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/sk/101010100.html"];
[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 反序列化
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:NULL];
NSLog(@"%@", result);
}] resume];
}
@end
// DemoViewController.swift
import UIKit
class DemoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://www.weather.com.cn/data/sk/101010100.html")
// `_` 表示忽略
// session默认超时时长 60s
NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, _, _) -> Void in
//模仿网络JSON数据
// JSON 是一个特殊格式的字符串
let jsonStr = "[\"hello\", \"world\"]"
let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding)
// 反序列化 - `throws` 2.0 的语法,捕获异常
//1.
do {
let result = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: [])
print(result)
} catch { // 如果反序列化失败,能够捕获到 json 失败的准确原因,而不会崩溃
print(error)
}
// OC 中的按位枚举的方式改为数组的方式设置 [值1, 值2]
// try! 程序员要负责,如果数据格式不正确,会崩溃!
//2.
let result = try! NSJSONSerialization.JSONObjectWithData(jsonData!, options: [NSJSONReadingOptions.MutableContainers, NSJSONReadingOptions.MutableLeaves])
//3.
guard let result = try? NSJSONSerialization.JSONObjectWithData(jsonData!, options: [NSJSONReadingOptions.MutableContainers, NSJSONReadingOptions.MutableLeaves]) else {
print("反序列化失败")
return
}
print(result)
}.resume()
}
}