欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

談?wù)刬OS開(kāi)發(fā)之JSON格式數(shù)據(jù)的生成與解析

 更新時(shí)間:2017年01月05日 11:28:56   作者:木木文  
JSON格式取代了xml給網(wǎng)絡(luò)傳輸帶來(lái)了很大的便利,本篇文章主要介紹了iOS開(kāi)發(fā):對(duì)象直接轉(zhuǎn)化成JSON詳解,具有一定的參考價(jià)值,有興趣的可以了解一下。

本文將從四個(gè)方面對(duì)IOS開(kāi)發(fā)中JSON格式數(shù)據(jù)的生成與解析進(jìn)行講解:

一、JSON是什么?

二、我們?yōu)槭裁匆肑SON格式的數(shù)據(jù)?

三、如何生成JSON格式的數(shù)據(jù)?

四、如何解析JSON格式的數(shù)據(jù)?

JSON格式取代了xml給網(wǎng)絡(luò)傳輸帶來(lái)了很大的便利,但是卻沒(méi)有了xml的一目了然,尤其是json數(shù)據(jù)很長(zhǎng)的時(shí)候,我們會(huì)陷入繁瑣復(fù)雜的數(shù)據(jù)節(jié)點(diǎn)查找中。這時(shí)我們就需要一款在線校驗(yàn)工具 BeJson。

一、JSON是什么?

JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式。它基于ECMAScript的一個(gè)子集。 JSON采用完全獨(dú)立于語(yǔ)言的文本格式,但是也使用了類似于C語(yǔ)言家族的習(xí)慣(包括C、C++、C#、Java、JavaScript、Perl、 Python等)。這些特性使JSON成為理想的數(shù)據(jù)交換語(yǔ)言。 易于人閱讀和編寫,同時(shí)也易于機(jī)器解析和生成(一般用于提升網(wǎng)絡(luò)傳輸速率)。

JSON數(shù)據(jù)主要有兩種數(shù)據(jù)結(jié)構(gòu),一種是鍵/值,另一種是數(shù)組的形式來(lái)表示。

1、JSON 數(shù)據(jù)的書寫格式是:名稱/值對(duì)。如:

{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"} 

2、JSON 數(shù)據(jù)的書寫格式是:數(shù)組格式,當(dāng)需要表示一組值時(shí),JSON 不但能夠提高可讀性,而且可以減少?gòu)?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 對(duì)象中表示的一組數(shù)據(jù)轉(zhuǎn)換為字符串,然后就可以在函數(shù)之間輕松地傳遞這個(gè)字符串,或者在異步應(yīng)用程序中將字符串從 Web 客戶機(jī)傳遞給服務(wù)器端程序。這個(gè)字符串看起來(lái)有點(diǎn)兒古怪,但是JavaScript很容易解釋它,而且 JSON 可以表示比"名稱 / 值對(duì)"更復(fù)雜的結(jié)構(gòu)。例如,可以表示數(shù)組和復(fù)雜的對(duì)象,而不僅僅是鍵和值的簡(jiǎn)單列表。

JSON作為數(shù)據(jù)包格式傳輸?shù)臅r(shí)候具有更高的效率,這是因?yàn)镴SON不像XML那樣需要有嚴(yán)格的閉合標(biāo)簽,這就讓有效數(shù)據(jù)量與總數(shù)據(jù)包比大大提升,從而減少同等數(shù)據(jù)流量的情況下,網(wǎng)絡(luò)的傳輸壓力。

三、如何生成JSON格式的數(shù)據(jù)?

1、利用字典NSDictionary轉(zhuǎn)換為鍵/值格式的數(shù)據(jù)。

// 如果數(shù)組或者字典中存儲(chǔ)了 NSString, NSNumber, NSArray, NSDictionary, or NSNull 之外的其他對(duì)象,就不能直接保存成文件了.也不能序列化成 JSON 數(shù)據(jù).
  NSDictionary *dict = @{@"name" : @"me", @"do" : @"something", @"with" : @"her", @"address" : @"home"};
  
  // 1.判斷當(dāng)前對(duì)象是否能夠轉(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是通過(guò)文件類型來(lái)確定數(shù)據(jù)類型的!如果不添加類型,有可能識(shí)別不了! 自己最好添加文件類型.
    [jsonData writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/dict.json" atomically:YES];
    
    NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    
  } else {
    
    NSLog(@"JSON數(shù)據(jù)生成失敗,請(qǐng)檢查數(shù)據(jù)格式");
    
  }

2、通過(guò)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ù)生成失敗,請(qǐng)檢查數(shù)據(jù)格式");
    
  }

四、如何解析JSON格式的數(shù)據(jù)?

1、使用TouchJSon解析方法:(需導(dǎo)入包:#import "TouchJson/JSON/CJSONDeserializer.h")

//使用TouchJson來(lái)解析北京的天氣
//獲取API接口
NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];

//定義一個(gè)NSError對(duì)象,用于捕獲錯(cuò)誤信息
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

NSLog(@"jsonString--->%@",jsonString);

//將解析得到的內(nèi)容存放字典中,編碼格式為UTF8,防止取值的時(shí)候發(fā)生亂碼
NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];

//因?yàn)榉祷氐腏son文件有兩層,去第二層內(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方法解析:(無(wú)需導(dǎo)入包,IOS5支持,低版本IOS不支持)

// 從中國(guó)天氣預(yù)報(bào)網(wǎng)請(qǐng)求數(shù)據(jù)
  NSURL *url = [ NSURL URLWithString:@"http://www.weather.com.cn/adat/sk/101010100.html"];
  
  // 創(chuàng)建請(qǐ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)中,要增加錯(cuò)誤機(jī)制.
    // 失敗機(jī)制處理: 錯(cuò)誤的狀態(tài)碼!
    
    // 最簡(jiǎn)單的錯(cuò)誤處理機(jī)制:
    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ù)字,可以使用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,如果再使用objectFromJSONString,程序可能會(huì)報(bào)錯(cuò)(測(cè)試結(jié)果表明:使用由網(wǎng)絡(luò)或得到的php/json_encode生成的json時(shí)會(huì)報(bào)錯(cuò),但使用NSString定義的json字符串時(shí),解析成功),最好使用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中解析方式的對(duì)比:

系統(tǒng)的API的解析速度最快。

SBJSON的解析速度為倒數(shù)第二差。

與系統(tǒng)API較為接近的是JSONKit。

在今后的開(kāi)發(fā)過(guò)程中,建議選用系統(tǒng)的API或JSONKit來(lái)對(duì)JSON數(shù)據(jù)進(jìn)行解析。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論