Objective-C中的Json解析,NSUTF8Encoding,

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

/* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
   The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
 */
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
/* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method.
 */
+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error;

 

 

 

 

 

 

 

解析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);
        
}

文章轉載自:http://www.tuicool.com/articles/AjArQb

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章