您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發(74):把 Array 與 Dictionary 序列化成 JSON

編輯:iOS 開發綜合

前言

App 與伺服器溝通時,最常見的任務就是把物件結構轉成 JSON 字串送出去。iOS 5 之後,系統內建了 NSJSONSerialization,不必再引入第三方庫,只要呼叫 dataWithJSONObject:options:error:,就能把 Array 與 Dictionary 序列化為 JSON 資料。

程式碼實作

-(void)converseToJson{
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:@"Archy" forKey:@"First Name"];
    [dictionary setValue:@"Robbins" forKey:@"Last Name"];
    [dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@"Age"];

    NSArray *arrayOfArchysChildren = [[NSArray alloc] initWithObjects:
                                      @"Anthony's Son 1",
                                      @"Anthony's Daughter 1",
                                      @"Anthony's Son 2",
                                      @"Anthony's Son 3",
                                      @"Anthony's Daughter 2", nil];
    [dictionary setValue:arrayOfArchysChildren forKey:@"children"];

    NSError *error = nil;

    // NSJSONWritingPrettyPrinted 會讓輸出的 JSON 帶有縮排與換行,便於閱讀;
    // 不設定這個選項時,會產生最精簡的表示法
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:dictionary
                        options:NSJSONWritingPrettyPrinted
                        error:&error];

    if ([jsonData length] > 0 && error == nil){
        NSLog(@"Successfully serialized the dictionary into data.");
        // 將 NSData 轉為字串
        NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                   encoding:NSUTF8StringEncoding];
        NSLog(@"JSON String = %@", jsonString);
    }
    else if ([jsonData length] == 0 && error == nil){
        NSLog(@"No data was returned after serialization.");
    }
    else if (error != nil){
        NSLog(@"An error happened = %@", error);
    }
}

輸出結果

2013-05-13 17:14:26.087 ToJsonTest[4890:303] Successfully serialized the dictionary into data.
2013-05-13 17:14:26.089 ToJsonTest[4890:303] JSON String = {
  "children" : [
    "Anthony's Son 1",
    "Anthony's Daughter 1",
    "Anthony's Son 2",
    "Anthony's Son 3",
    "Anthony's Daughter 2"
  ],
  "Age" : 51,
  "First Name" : "Archy",
  "Last Name" : "Robbins"
}

幾個實務重點

  • 可序列化的型別有限:只有 NSString、NSNumber、NSArray、NSDictionary 與 NSNull 能直接處理。自訂物件要先轉成字典再序列化。
  • key 必須是字串:非字串的 key 會導致執行期例外。
  • 反方向也能做:用 JSONObjectWithData:options:error: 即可把 JSON 資料還原成 dictionary/array,是解析 API 回應的標準做法。
  • 錯誤處理別省:JSON 格式不合法時會回傳 nil 並填入 NSError,正式環境務必檢查,避免拿到 nil 後才在別處崩潰。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved