Objective-C ,ios,iphone開發基礎:JSON解析(使用蘋果官方提供的JSON庫:NSJSONSerialization)__JSON

來源:互聯網
上載者:User

json和xml的普及個人覺得是為了簡化閱讀難度,以及減輕網路負荷,json和xml 資料格式在格式化以後都是一種樹狀結構,可以樹藤摸瓜的得到你想要的任何果子。

而不格式化的時候json和xml 又是一個普普通通的字串,在網路通訊的時候也只需要請求一次,而不用每次為得到木一個值而重複的請求伺服器或者目標主機,

json和xml 都採用 鍵 - 值 的形式來存放資料。

xml 使用: <鍵> 值 </鍵>

json 使用:  "鍵" : "值"

蘋果公司提供了一個官方的json解析庫 NSJSONSerialization   

NSJSONSerialization  裡麵包含了兩個方法來通過不同資料形式來解析json資料。

1、+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error; //使用緩衝區資料來解析

2、+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error; // 使用檔案流的形式來解析json

 

解析json的步驟大概是,先把json字串讀取到緩衝區,然後使用NSJSONSerialization    裡面的方法進行解析,根據不同json 格式可能返回的資料類型不一樣,所以最好用 id 類型接。

eg:  id dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];

在得到解析後的資料時,然後就一步一步 ,一個一個 鍵 - 值 的去尋找你想要的咚咚。

 

Eg 1 : 從本地檔案中讀取json資料,然後讀取到緩衝區。


- (void)jsonParse{       //初始設定檔案路徑。    NSString* path  = [[NSBundle mainBundle] pathForResource:@"nanjing" ofType:@"txt"];   //將檔案內容讀取到字串中,注意編碼NSUTF8StringEncoding 防止亂碼,    NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];   //將字串寫到緩衝區。    NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];    //解析json資料,使用系統方法 JSONObjectWithData:  options: error:    NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];    //接下來一步一步解析。知道得到你想要的東西。    NSArray* arrayResult =[dic objectForKey:@"results"];     NSDictionary* resultDic = [arrayResult objectAtIndex:0];    NSDictionary* geometryDic = [resultDic objectForKey:@"geometry"];    NSLog(@"geometryDic: %@,  resultDic:%@",geometryDic,resultDic);    NSDictionary* locationDic = [geometryDic objectForKey:@"location"];    NSNumber* lat = [locationDic objectForKey:@"lat"];    NSNumber* lng = [locationDic objectForKey:@"lng"];    NSLog(@"lat = %@, lng = %@",lat,lng);    [jsonString release];        }

 

 

Eg 2 :使用網路路徑來解析json,

- (void)jsonParse{       //初始化網路路徑。    NSString* path  = @"http://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true";    //初始化 url     NSURL* url = [NSURL URLWithString:path];   //將檔案內容讀取到字串中,注意編碼NSUTF8StringEncoding 防止亂碼,    NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];   //將字串寫到緩衝區。    NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];    //解析json資料,使用系統方法 JSONObjectWithData:  options: error:    NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];        //一下為自訂解析, 自己想怎麼幹就怎麼幹        NSArray* arrayResult =[dic objectForKey:@"results"];     NSDictionary* resultDic = [arrayResult objectAtIndex:0];    NSDictionary* geometryDic = [resultDic objectForKey:@"geometry"];    NSLog(@"geometryDic: %@,  resultDic:%@",geometryDic,resultDic);    NSDictionary* locationDic = [geometryDic objectForKey:@"location"];    NSNumber* lat = [locationDic objectForKey:@"lat"];    NSNumber* lng = [locationDic objectForKey:@"lng"];    NSLog(@"lat = %@, lng = %@",lat,lng);    [jsonString release];        }

 


Eg 3 :使用網路路徑來解析json 。 使用NSURLRequest 和NSURLConnection 請求網路資料。

- (void)jsonParse{       //初始化網路路徑。    NSString* path  = @"http://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true";    //初始化 url     NSURL* url = [NSURL URLWithString:path];    NSURLRequest* request = [NSURLRequest requestWithURL:url];    //將請求到的字串寫到緩衝區。    NSData* jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];    //解析json資料,使用系統方法 JSONObjectWithData:  options: error:    NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];        //一下為自訂解析, 自己想怎麼幹就怎麼幹        NSArray* arrayResult =[dic objectForKey:@"results"];     NSDictionary* resultDic = [arrayResult objectAtIndex:0];    NSDictionary* geometryDic = [resultDic objectForKey:@"geometry"];    NSLog(@"geometryDic: %@,  resultDic:%@",geometryDic,resultDic);    NSDictionary* locationDic = [geometryDic objectForKey:@"location"];    NSNumber* lat = [locationDic objectForKey:@"lat"];    NSNumber* lng = [locationDic objectForKey:@"lng"];    NSLog(@"lat = %@, lng = %@",lat,lng);        }

demo下載 :http://download.csdn.net/download/wsq724439564/6207829

                                     

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.