本文將從四個方面對IOS開發(fā)中JSON格式數(shù)據(jù)的生成與解析進行講解:
一、JSON是什么?
二、我們?yōu)槭裁匆肑SON格式的數(shù)據(jù)?
三、如何生成JSON格式的數(shù)據(jù)?
四、如何解析JSON格式的數(shù)據(jù)?
JSON格式取代了xml給網(wǎng)絡(luò)傳輸帶來了很大的便利,但是卻沒有了xml的一目了然,尤其是json數(shù)據(jù)很長的時候,我們會陷入繁瑣復(fù)雜的數(shù)據(jù)節(jié)點查找中。這時我們就需要一款在線校驗工具 BeJson。
一、JSON是什么?
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。它基于ECMAScript的一個子集。 JSON采用完全獨立于語言的文本格式,但是也使用了類似于C語言家族的習(xí)慣(包括C、C++、C#、Java、JavaScript、Perl、 Python等)。這些特性使JSON成為理想的數(shù)據(jù)交換語言。 易于人閱讀和編寫,同時也易于機器解析和生成(一般用于提升網(wǎng)絡(luò)傳輸速率)。
JSON數(shù)據(jù)主要有兩種數(shù)據(jù)結(jié)構(gòu),一種是鍵/值,另一種是數(shù)組的形式來表示。
1、JSON 數(shù)據(jù)的書寫格式是:名稱/值對。如:
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
2、JSON 數(shù)據(jù)的書寫格式是:數(shù)組格式,當(dāng)需要表示一組值時,JSON 不但能夠提高可讀性,而且可以減少復(fù)雜性。如:
{ "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" }]}
二、我們?yōu)槭裁匆肑SON格式的數(shù)據(jù)?
JSON 可以將 JavaScript 對象中表示的一組數(shù)據(jù)轉(zhuǎn)換為字符串,然后就可以在函數(shù)之間輕松地傳遞這個字符串,或者在異步應(yīng)用程序中將字符串從 Web 客戶機傳遞給服務(wù)器端程序。這個字符串看起來有點兒古怪,但是JavaScript很容易解釋它,而且 JSON 可以表示比"名稱 / 值對"更復(fù)雜的結(jié)構(gòu)。例如,可以表示數(shù)組和復(fù)雜的對象,而不僅僅是鍵和值的簡單列表。
JSON作為數(shù)據(jù)包格式傳輸?shù)臅r候具有更高的效率,這是因為JSON不像XML那樣需要有嚴(yán)格的閉合標(biāo)簽,這就讓有效數(shù)據(jù)量與總數(shù)據(jù)包比大大提升,從而減少同等數(shù)據(jù)流量的情況下,網(wǎng)絡(luò)的傳輸壓力。
三、如何生成JSON格式的數(shù)據(jù)?
1、利用字典NSDictionary轉(zhuǎn)換為鍵/值格式的數(shù)據(jù)。
// 如果數(shù)組或者字典中存儲了 NSString, NSNumber, NSArray, NSDictionary, or NSNull 之外的其他對象,就不能直接保存成文件了.也不能序列化成 JSON 數(shù)據(jù). NSDictionary *dict = @{@"name" : @"me", @"do" : @"something", @"with" : @"her", @"address" : @"home"}; // 1.判斷當(dāng)前對象是否能夠轉(zhuǎn)換成JSON數(shù)據(jù). // YES if obj can be converted to JSON data, otherwise NO BOOL isYes = [NSJSONSerialization isValidJSONObject:dict]; if (isYes) { NSLog(@"可以轉(zhuǎn)換"); /* JSON data for obj, or nil if an internal error occurs. The resulting data is a encoded in UTF-8. */ NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL]; /* Writes the bytes in the receiver to the file specified by a given path. YES if the operation succeeds, otherwise NO */ // 將JSON數(shù)據(jù)寫成文件 // 文件添加后綴名: 告訴別人當(dāng)前文件的類型. // 注意: AFN是通過文件類型來確定數(shù)據(jù)類型的!如果不添加類型,有可能識別不了! 自己最好添加文件類型. [jsonData writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/dict.json" atomically:YES]; NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]); } else { NSLog(@"JSON數(shù)據(jù)生成失敗,請檢查數(shù)據(jù)格式"); }
2、通過JSON序列化可以轉(zhuǎn)換數(shù)組,但轉(zhuǎn)換結(jié)果不是標(biāo)準(zhǔn)化的JSON格式。
NSArray *array = @[@"qn", @18, @"ya", @"wj"]; BOOL isYes = [NSJSONSerialization isValidJSONObject:array]; if (isYes) { NSLog(@"可以轉(zhuǎn)換"); NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL]; [data writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/base" atomically:YES]; } else { NSLog(@"JSON數(shù)據(jù)生成失敗,請檢查數(shù)據(jù)格式"); }
四、如何解析JSON格式的數(shù)據(jù)?
1、使用TouchJSon解析方法:(需導(dǎo)入包:#import "TouchJson/JSON/CJSONDeserializer.h")
//使用TouchJson來解析北京的天氣//獲取API接口NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];//定義一個NSError對象,用于捕獲錯誤信息NSError *error;NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];NSLog(@"jsonString--->%@",jsonString);//將解析得到的內(nèi)容存放字典中,編碼格式為UTF8,防止取值的時候發(fā)生亂碼NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];//因為返回的Json文件有兩層,去第二層內(nèi)容放到字典中去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解析方法:(需導(dǎo)入包:#import "SBJson/SBJson.h")
//使用SBJson解析北京的天氣NSURL *url = [NSURL URLWithString:@"http://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、使用IOS5自帶解析類NSJSONSerialization方法解析:(無需導(dǎo)入包,IOS5支持,低版本IOS不支持)
// 從中國天氣預(yù)報網(wǎng)請求數(shù)據(jù) NSURL *url = [ NSURL URLWithString:@"http://www.weather.com.cn/adat/sk/101010100.html"]; // 創(chuàng)建請求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // 在網(wǎng)絡(luò)完成的 Block 回調(diào)中,要增加錯誤機制. // 失敗機制處理: 錯誤的狀態(tài)碼! // 最簡單的錯誤處理機制: if (data && !error) { // JSON格式轉(zhuǎn)換成字典,IOS5中自帶解析類NSJSONSerialization從response中解析出數(shù)據(jù)放到字典中 id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; NSDictionary *dict = obj[@"weatherinfo"]; NSLog(@"%@---%@", dict, dict[@"city"]); } }] resume];
4、使用JSONKit的解析方法:(需導(dǎo)入包:#import "JSONKit/JSONKit.h")
//如果json是“單層”的,即value都是字符串、數(shù)字,可以使用objectFromJSONStringNSString *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,如果再使用objectFromJSONString,程序可能會報錯(測試結(jié)果表明:使用由網(wǎng)絡(luò)或得到的php/json_encode生成的json時會報錯,但使用NSString定義的json字符串時,解析成功),最好使用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"]);
友好提示:
4中解析方式的對比:
系統(tǒng)的API的解析速度最快。
SBJSON的解析速度為倒數(shù)第二差。
與系統(tǒng)API較為接近的是JSONKit。
在今后的開發(fā)過程中,建議選用系統(tǒng)的API或JSONKit來對JSON數(shù)據(jù)進行解析。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答