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

用 NSJSONSerialization 解析 JSON:以 Google 地理資訊 API 為例

編輯:iOS 開發綜合

iOS 上處理 JSON 早期得靠 SBJSON 這類第三方套件。自 iOS 5 起,系統內建了 NSJSONSerialization,不必再引入外部相依,也更方便後續維護與升級。

核心方法與三個 options

+ (id)JSONObjectWithData:(NSData *)data
                 options:(NSJSONReadingOptions)opt
                   error:(NSError **)error;

依 data 的結構不同,要搭配不同的 option:

  • NSJSONReadingMutableContainers:產生的陣列與字典為 mutable,可直接修改。
  • NSJSONReadingMutableLeaves:JSON 物件圖中的葉節點字串建立為 NSMutableString 實例。
  • NSJSONReadingAllowFragments:允許最外層不是 NSArray 或 NSDictionary 的物件(iOS 5.0 以後)。這個在解析單一數字或字串時才需要。

範例資料:Google Geocoding API

這個 API 依地點名稱回傳經緯度等資訊,回應是典型的巢狀結構:

{
  "results" : [
    {
      "address_components" : [
        { "long_name" : "南京",   "short_name" : "南京",   "types" : ["locality", "political"] },
        { "long_name" : "江蘇省", "short_name" : "江蘇省", "types" : ["administrative_area_level_1", "political"] },
        { "long_name" : "中國",   "short_name" : "CN",     "types" : ["country", "political"] }
      ],
      "formatted_address" : "中國江蘇省南京市",
      "geometry" : {
        "bounds" : { "northeast" : {...}, "southwest" : {...} },
        "location" : { "lat" : 32.0602550, "lng" : 118.7968770 },
        "location_type" : "APPROXIMATE",
        "viewport" : { "northeast" : {...}, "southwest" : {...} }
      },
      "types" : ["locality", "political"]
    }
  ],
  "status" : "OK"
}

這份資料的層次是:最外層字典 → results 陣列 → 每個元素又是字典 → geometry 字典 → location 字典 → lat / lng 字串。解析時必須照著這個路徑一層層往下走。

解析步驟

第一步:把整份資料解析成字典。

NSError *error = nil;
NSDictionary *resultsDic = [NSJSONSerialization JSONObjectWithData:data
                                                          options:NSJSONReadingMutableContainers
                                                            error:&error];

第二步:取出 results 對應的陣列。

NSArray *resultsArr = [resultsDic objectForKey:@"results"];

第三步:遍歷陣列,每個元素都是一個字典,逐層往下取。

for (NSDictionary *resultDetailDic in resultsArr) {
    NSDictionary *locationDic = [[resultDetailDic objectForKey:@"geometry"] objectForKey:@"location"];
    NSString *lat = [locationDic objectForKey:@"lat"];
    NSString *lng = [locationDic objectForKey:@"lng"];

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"lat = %@", lat);
        NSLog(@"lng = %@", lng);
    });
}

注意 dispatch_async 的用法:網路回應通常在背景佇列,任何 UI 更新都必須切回主執行緒,否則會出現畫面不更新甚至崩潰。

完整範例

- (void)parseJson:(NSString *)addr {
    NSString *_urlString = @"https://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true";
    NSURL *_url = [NSURL URLWithString:_urlString];
    NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:_url];
    [_request setValue:@"application/json" forHTTPHeaderField:@"accept"];

    [NSURLConnection sendAsynchronousRequest:_request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        NSLog(@"status code = %ld", (long)[httpResponse statusCode]);

        NSError *_errorJson = nil;
        NSDictionary *resultsDic = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:NSJSONReadingMutableContainers
                                                                    error:&_errorJson];
        if (_errorJson != nil) {
            NSLog(@"Error %@", [_errorJson localizedDescription]);
            return;
        }

        NSString *resultStatus = [resultsDic objectForKey:@"status"];
        if ([resultStatus isEqualToString:@"OK"]) {
            NSArray *resultsArr = [resultsDic objectForKey:@"results"];
            for (NSDictionary *resultDetailDic in resultsArr) {
                NSDictionary *locationDic = [[resultDetailDic objectForKey:@"geometry"]
                                                                            objectForKey:@"location"];
                NSString *lat = [locationDic objectForKey:@"lat"];
                NSString *lng = [locationDic objectForKey:@"lng"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"lat = %@", lat);
                    NSLog(@"lng = %@", lng);
                });
            }
        }
    }];
}

讓解析更「強壯」

上面的寫法對資料結構依賴很緊:只要伺服器改了欄位名稱、或某筆資料缺少 geometry,objectForKey: 會回傳 nil,接著對 nil 再取 key 雖然不會崩潰,但會安靜地拿到 nil,問題被藏起來。

實務上建議加上型別檢查:

id geometry = [resultDetailDic objectForKey:@"geometry"];
if (![geometry isKindOfClass:[NSDictionary class]]) continue;

id location = [geometry objectForKey:@"location"];
if (![location isKindOfClass:[NSDictionary class]]) continue;

另外別忘了先檢查最外層的 status 欄位。Google 這類 API 在配額用盡或參數錯誤時會回傳 REQUEST_DENIED、OVER_QUERY_LIMIT 等狀態,此時 results 陣列可能不存在,直接取用只會得到空集合而看不出錯誤原因。

最後提醒:範例中的 URL 使用 http,在 iOS 9 以後會被 App Transport Security 攔下,正式環境請改用 https。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved