iOS網絡編程:網絡交互數據格式解析之json

    JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,目前在網絡交互過程當中有着舉足輕重的地位。若是您對 json 還有什麼不清楚的話建議去看 json百度百科

    在iOS平臺上,Apple 從 iOS 5.0 纔開始提供原生的json生成和解析的API,使用起來 很是方便,但這樣就沒法爲iOS 5.0 以前版本的用戶服務了。對於iOS 5.0之前的系統,json的使用得益於無數無私的開源擁護者的貢獻。估計大多數開發者如今還不會直接拋棄仍在使用 5.0 之前版本的用戶,因此這裏優先介紹3種主要的開源庫的使用,而後再介紹新的原生API的使用。
html

    測試數據咱們使用國家氣象局提供的天氣預報接口 git

     您能夠用瀏覽器打開,看看這三個地址究竟是什麼--其實你能夠分別看到3個字符串,沒錯,你纔對了,這就是咱們測試用的 json 數據。

    咱們打開 github 搜索關鍵字 json ,程序語言選擇 Objective-C ;能夠獲得 n 頁結果。咱們就依次介紹最前面的3個:stig/json-framework、TouchCode/TouchJSON、johnezang/JSONKit。緊接着介紹 iOS 5.0 開始提供的原生 JSON 處理類。 github

    此處咱們將這三個開源庫及原生JSON處理類放到一個工程裏介紹了,但開源庫 stig/json-framework 編譯是須要ARC支持的,而TouchCode/TouchJSON 和 johnezang/JSONKit 是不須要 ARC 支持。這樣我麼在工程中就須要打開 ARC (能夠在建立工程的時候就選中 ARC,也可和下圖同樣在build setting 中設置兩處 爲 YES) 編程



而後對後二者在編譯規則中作簡單的處理,-fno-objc-arc便是規定該文件編譯時不須要ARC支持,以下圖:
json



由於咱們測試的數據來自於互聯網,因此咱們須要網絡支持,這裏咱們須要添加系統庫:CFNetwork.framework,以下圖 瀏覽器



終於開始寫代碼了,公用代碼: 網絡

1.將url地址定義成字符串常量 異步

2.import 相應文件; 測試

3.鏈接到測試的url; ui

4.取得json數據,並將其以字符串的形式顯示在第一個 TextView 上;

5.將解析後的JSON實際內容顯示在第二個 TextView 上。

//爲了方便,先在工程中的 .pch 文件中定義 字符串常量

#define jsonSourceURLAddress_1 @"http://m.weather.com.cn/data/101010100.html"
#define jsonSourceURLAddress_2 @"http://www.weather.com.cn/data/sk/101010100.html"
#define jsonSourceURLAddress_3 @"http://www.weather.com.cn/data/cityinfo/101010100.html

#import "LTRootViewController.h"

//測試工程中 3 中方式都是在這個controller中使用,將須要的import進來

#import "SBJson.h"

#import "TouchJSON/JSON/CJSONDeserializer.h"

#import "JSONKit/JSONKit.h"
- (void)viewDidLoad
{
    [super viewDidLoad];
    //向開源的地址發送鏈接請求
    //這裏使用的是異步的請求
    NSURL *url = [NSURL URLWithString:jsonSourceURLAddress_1];
    NSURLRequest    *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
    NSURLConnection *urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    [urlConnection start];
}
#pragma mark - NSURLConnectionDataDelegate methods
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView * alertV = [[UIAlertView alloc] initWithTitle:@"網絡鏈接失敗" message:[NSString  stringWithFormat:@"%@",error] delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alertV show];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //這裏咱們終於拿到了網絡返回的 JSON 數據 data
    self.m_JsonData = data;
    self.m_sourceJsonTV.text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
- (void)displayWithParsedDic:(NSDictionary *)rootDic
{
    //rootDic 來自與咱們所用的各類方式將 JSON 解析後獲得的字典
    //下面用於在 TextView 中顯示解析成功的JSON實際內容
    if (!rootDic) {
        self.m_parsedJsonTV.text = @"cleaned...";
    }else{
        NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
        //因爲字典中內容太多,咱們只顯示了一部分,諸如 temp2,temp3,...咱們木有在這一一顯示
        self.m_parsedJsonTV.text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天氣情況是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
    }
}


    如今分類的介紹這4種JSON解析方式:

一、json-framework

    也有人管這庫叫SBJson咱們從 github 上下載 json-framework這個庫並將其導入到咱們的工程中(僅需將下載下來的文件夾中,classes 目錄下的全部文件複製導入到咱們的工程就行)。在任何你須要使用json處 :#import "SBJson.h" 

- (IBAction)sbjsonAction:(id)sender {
    //此處是使用 json-framework (SBJSON)解析,獲得解析後存入字典:rootDic,並顯示
    SBJsonParser * parser = [[SBJsonParser alloc] init];
    NSString * jsonStr = [[NSString alloc] initWithData:self.m_JsonData encoding:NSUTF8StringEncoding];
    NSDictionary *rootDic = [parser objectWithString:jsonStr];
    [self displayWithParsedDic:rootDic];
}


二、TouchJSON

    我糾結了好久,要不要介紹這個庫了,由於做者在github上聲稱"But you should NOT be using this code in your new projects"。

    咱們從 github 上下載 TouchCode/TouchJSON 這個庫並將其導入到咱們的工程中(僅需將下載下來的文件夾中,Source 目錄下的全部文件複製導入到咱們的工程)。可是 Source/Experimental目錄下提供的功能慎用( Be aware that the code in the Experimental subdirectory of Source is just that and may not have been extensively tested and/or have extra dependencies)。在任何你須要使用json處:#import "CJSONDeserializer.h" 

- (IBAction)touchJsonAction:(id)sender {
    //此處是使用 TouchJSON 解析,獲得解析後存入字典:rootDic,並顯示
    NSError * error = nil;//error 用來存儲解析過程當中可能出現的錯誤信息
    NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:self.m_JsonData error:&error];
    [self displayWithParsedDic:rootDic];
}


三、JSONKit

    咱們從 github 上下載 johnezang/JSONKit 這個庫並將其導入到咱們的工程中(這個很簡單,代碼文件只有2個,都複製導入咱們的工程吧)。

- (IBAction)jsonkitAction:(id)sender {
    //此處是使用 JSONKit 解析,獲得解析後存入字典:rootDic,並顯示
    NSDictionary * rootDic = [self.m_JsonData objectFromJSONDataWithParseOptions:JKParseOptionLooseUnicode];
    [self displayWithParsedDic:rootDic];
}


四、原生JSON處理類

    使用原生的JSON處理類解析就至關方便了,聽說也是最快的(未親測速度):
- (IBAction)nsjsonAction:(id)sender {
    //此處是使用原生的 JSON 處理類解析,獲得解析後存入字典:rootDic,並顯示
    NSError *error = nil;
    NSDictionary * rootDic = [NSJSONSerialization JSONObjectWithData:self.m_JsonData options:NSJSONReadingMutableLeaves error:&error];
    [self displayWithParsedDic:rootDic];
}


    小結:這裏只是介紹了最簡單的經過網絡獲得JSON並解析之的方法。在實際應用中咱們可能還要主意在解析時,根據實際傳輸的數據須要設置的 option 類型。因爲本人的水平有限,若是有錯我還請各位拍磚,並點出來我必定第一時間更正。

(專門爲這篇文章寫的demo,貌似oschina木有辦法以附件的形式上傳。唉!)

    經過共享代碼上傳了 Demo——iOS網絡編程:

網絡交互數據格式解析之JSON的Demo

相關文章
相關標籤/搜索