JSON 幾乎完全取代了 XML 成為網路傳輸的主流格式,但它不像 XML 那樣有明確的閉合標籤,一眼看不出結構。資料一長,很容易陷入層層節點的查找迷宮。本文從四個角度整理:JSON 是什麼、為什麼用它、怎麼產生、怎麼解析。
JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,基於 ECMAScript 的子集,但採用完全獨立於語言的純文字形式,並沿用了 C 語言家族(C、C++、C#、Java、JavaScript、Perl、Python 等)的習慣寫法。這些特性讓它同時易於人閱讀撰寫、易於機器解析產生,也因此在傳輸效率上有優勢。
JSON 主要有兩種結構:鍵/值對,以及陣列。
(1)名稱/值對:
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
(2)陣列形式,當需要表示一組值時,可讀性與結構都更好:
{
"programmers": [
{"firstName":"Brett", "lastName":"McLaughlin", "email":"aaaa"},
{"firstName":"Elliotte", "lastName":"Harold", "email":"cccc"}
],
"authors": [
{"firstName":"Isaac", "lastName":"Asimov", "genre":"sciencefiction"},
{"firstName":"Frank", "lastName":"Peretti", "genre":"christianfiction"}
],
"musicians": [
{"firstName":"Eric", "lastName":"Clapton", "instrument":"guitar"},
{"firstName":"Sergei", "lastName":"Rachmaninoff", "instrument":"piano"}
]
}
遇到難讀的長 JSON,可以貼到線上 JSON 校驗工具(例如 BeJson)格式化後再看,效率差很多。
JSON 能把一組 JavaScript 物件資料序列化成字串,就能在函式之間傳遞,或在非同步情境下從用戶端送到伺服器。JavaScript 天生就能解析它,而且 JSON 能表達的結構遠比「名稱/值對」清單複雜,陣列與巢狀物件都支援。
更關鍵的是傳輸效率:JSON 不需要像 XML 那樣為每個節點加上成對的閉合標籤,因此「有效資料量/總封包大小」的比例高得多。同樣的資料量下,網路壓力明顯較小。
(1)用 NSDictionary 轉成鍵/值格式:
// 如果數組或者字典中存儲了 NSString, NSNumber, NSArray, NSDictionary, or NSNull
// 之外的其他對象, 就不能直接保存成文件, 也不能序列化成 JSON 數據.
NSDictionary *dict = @{@"name": @"me", @"do": @"something",
@"with": @"her", @"address": @"home"};
// 1.判斷當前對象是否能夠轉換成JSON數據
BOOL isYes = [NSJSONSerialization isValidJSONObject:dict];
if(isYes) {
NSLog(@"可以轉換");
// 轉換後的 data 以 UTF-8 編碼
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
// 將JSON數據寫成文件。建議補上副檔名,讓別人(以及工具)知道檔案類型
[jsonData writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/dict.json" atomically:YES];
NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
}else{
NSLog(@"JSON數據生成失敗,請檢查數據格式");
}
這裡有個容易忽略的限制:只有 NSString、NSNumber、NSArray、NSDictionary、NSNull 這幾種類型能被序列化,自訂的 model 物件必須先轉成字典才行。
(2)陣列也能序列化,但輸出不見得是標準化的 JSON 格式:
NSArray *array = @[@"qn", @18, @"ya", @"wj"];
BOOL isYes = [NSJSONSerialization isValidJSONObject:array];
if(isYes) {
NSLog(@"可以轉換");
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
[data writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/base" atomically:YES];
}else{
NSLog(@"JSON數據生成失敗,請檢查數據格式");
}
(1)TouchJson(需引入 #import "TouchJson/JSON/CJSONDeserializer.h"):
//使用TouchJson來解析北京的天氣
NSURL *url = [NSURL URLWithString:@"https://m.weather.com.cn/data/101010100.html"];
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(@"jsonString--->%@",jsonString);
//編碼格式為UTF8,防止取值時發生亂碼
NSDictionary *rootDic = [[CJSONDeserializer deserializer]
deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
error:&error];
//因為返回的Json文件有兩層,去第二層內容放到字典中去
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"weatherInfo--->%@",weatherInfo);
NSLog(@"%@",[NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@ ",
[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],
[weatherInfo objectForKey:@"city"],[weatherInfo objectForKey:@"weather1"],
[weatherInfo objectForKey:@"temp1"]]);
(2)SBJson(需引入 #import "SBJson/SBJson.h"):
//使用SBJson解析北京的天氣
NSURL *url = [NSURL URLWithString:@"https://www.weather.com.cn/adat/sk/101010100.html"];
NSError *error = nil;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"%@", [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@ ",
[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],
[weatherInfo objectForKey:@"city"],[weatherInfo objectForKey:@"weather1"],
[weatherInfo objectForKey:@"temp1"]]);
(3)iOS 5 之後系統自帶的 NSJSONSerialization(不需引入外部庫):
// 從中國天氣預報網請求數據
NSURL *url = [NSURL URLWithString:@"https://www.weather.com.cn/adat/sk/101010100.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
// 最簡單的錯誤處理機制
if(data && !error) {
// JSON格式轉換成字典
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSDictionary *dict = obj[@"weatherinfo"];
NSLog(@"%@---%@", dict, dict[@"city"]);
}
}] resume];
(4)JSONKit(需引入 #import "JSONKit/JSONKit.h"):
//如果json是"單層"的,即value都是字符串、數字,可以使用objectFromJSONString
NSString *json1 = @"{\"a\":123, \"b\":\"abc\"}";
NSLog(@"json1:%@",json1);
NSDictionary *data1 = [json1 objectFromJSONString];
NSLog(@"json1.a:%@",[data1 objectForKey:@"a"]);
NSLog(@"json1.b:%@",[data1 objectForKey:@"b"]);
//如果json有嵌套,即value裡有array、object,最好使用
//objectFromJSONStringWithParseOptions:
NSString *json2 = @"{\"a\":123, \"b\":\"abc\", \"c\":[456, \"hello\"], \"d\":{\"name\":\"張三\", \"age\":\"32\"}}";
NSLog(@"json2:%@", json2);
NSDictionary *data2 = [json2 objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);
NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);
就解析速度而言,系統自帶的 NSJSONSerialization 最快,JSONKit 與它相當接近,SBJson 則明顯較慢。
結論很清楚:新專案直接用系統 API。它效能最好、不必維護第三方依賴、也不會遇到包裹庫停止更新的問題。只有在需要支援非常舊的 iOS 版本時,才需要考慮 JSONKit 這類方案。
最後提醒:無論用哪一種,解析結果都是 id,取用巢狀資料前請確認型別與 key 是否存在。伺服器回傳格式變動是線上 crash 的常見原因,別假設資料永遠如你所料。