1. 程式人生 > >iOS開發之JSON格式數據的生成與解析

iOS開發之JSON格式數據的生成與解析

添加 json intern 對象 RM use convert mail value

我們為什麽要用JSON格式的數據?

JSON格式取代了xml給網絡傳輸帶來了很大的便利,但是卻沒有了xml的一目了然,尤其是json數據很長的時候,我們會陷入繁瑣復雜的數據節點查找中。這時我們就需要一款在線校驗工具 BeJson。

一、JSON是什麽?

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

JSON數據主要有兩種數據結構,一種是鍵/值,另一種是數組的形式來表示。

1、JSON 數據的書寫格式是:名稱/值對。如:

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

2、JSON 數據的書寫格式是:數組格式,當需要表示一組值時,JSON 不但能夠提高可讀性,而且可以減少復雜性。如:

{
    "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 可以將 JavaScript 對象中表示的一組數據轉換為字符串,然後就可以在函數之間輕松地傳遞這個字符串,或者在異步應用程序中將字符串從 Web 客戶機傳遞給服務器端程序。這個字符串看起來有點兒古怪,但是JavaScript很容易解釋它,而且 JSON 可以表示比"名稱 / 值對"更復雜的結構。例如,可以表示數組和復雜的對象,而不僅僅是鍵和值的簡單列表。

  JSON作為數據包格式傳輸的時候具有更高的效率,這是因為JSON不像XML那樣需要有嚴格的閉合標簽,這就讓有效數據量與總數據包比大大提升,從而減少同等數據流量的情況下,網絡的傳輸壓力。


三、如何生成JSON格式的數據?

1、利用字典NSDictionary轉換為鍵/值格式的數據。

// 如果數組或者字典中存儲了  NSString, NSNumber, NSArray, NSDictionary, or NSNull 之外的其他對象,就不能直接保存成文件了.也不能序列化成 JSON 數據.
    NSDictionary *dict = @{@"name" : @"me", @"do" : @"something", @"with" : @"her", @"address" : @"home"};
    
    // 1.判斷當前對象是否能夠轉換成JSON數據.
    // YES if obj can be converted to JSON data, otherwise NO
    BOOL isYes = [NSJSONSerialization isValidJSONObject:dict];
    
    if (isYes) {
        NSLog(@"可以轉換");
        
        /* 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數據寫成文件
        // 文件添加後綴名: 告訴別人當前文件的類型.
        // 註意: AFN是通過文件類型來確定數據類型的!如果不添加類型,有可能識別不了! 自己最好添加文件類型.
        [jsonData writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/dict.json" atomically:YES];
        
        NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
        
    } else {
        
        NSLog(@"JSON數據生成失敗,請檢查數據格式");
        
    }

2、通過JSON序列化可以轉換數組,但轉換結果不是標準化的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數據生成失敗,請檢查數據格式");
        
    }

四、如何解析JSON格式的數據?

1、使用TouchJSon解析方法:(需導入包:#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);

//將解析得到的內容存放字典中,編碼格式為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:@"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方法解析:(無需導入包,IOS5支持,低版本IOS不支持)

// 從中國天氣預報網請求數據
    NSURL *url = [ NSURL URLWithString:@"http://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) {
        
        // 在網絡完成的 Block 回調中,要增加錯誤機制.
        // 失敗機制處理: 錯誤的狀態碼!
        
        // 最簡單的錯誤處理機制:
        if (data && !error) {
            
            // JSON格式轉換成字典,IOS5中自帶解析類NSJSONSerialization從response中解析出數據放到字典中
            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,如果再使用objectFromJSONString,程序可能會報錯(測試結果表明:使用由網絡或得到的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中解析方式的對比:

系統的API的解析速度最快。

SBJSON的解析速度為倒數第二差。

與系統API較為接近的是JSONKit。

在今後的開發過程中,建議選用系統的API或JSONKit來對JSON數據進行解析。

iOS開發之JSON格式數據的生成與解析