[iOS] Objective-c 對的Json操作(二) JsonData Transfer to Object

  • 2711
  • 0
  • iOS
  • 2015-02-26

摘要:[iOS] Objective-c 對的Json操作(二)

上一篇文章提到如何操作Json資料,不過是以NSDictionary<key,value>的方式在存取資料。當資料結構一複雜的話,操作起資料就沒有那麼直覺。以上一個範例來看,從Facebook API提供的個人資料,我們將他貼到Json to C#的網站,可以得到下面的類別結構。

 

因為沒有一個到目前還沒看到有類似Json to C#的網站幫我們把Json轉成Objective-c的類別,所以要認命一點自己轉。

底下這段C#的類別檔案我們要自行把它翻譯成Objective-c的

public class RootObject
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string gender { get; set; }
    public string last_name { get; set; }
    public string locale { get; set; }
    public string name { get; set; }
    public string username { get; set; }
}

 

在Xcode的Command Line專案裡面,建立一個Object.h的Header檔案,來撰寫相關Objective-c物件。

眼尖的話,有發現我的物件不是繼承NSObject,而是繼承Jastor這個類別嗎?稍後再來介紹這個類別。

#import 
#import "Jastor.h"
@interface RootObject : Jastor
	@property (nonatomic) NSString* Id;
	@property (nonatomic) NSString* first_name;
	@property (nonatomic) NSString* gender;
	@property (nonatomic) NSString* last_name;
	@property (nonatomic) NSString* locale;
	@property (nonatomic) NSString* name;
	@property (nonatomic) NSString* username;
@end

 

在建立一個Objet.m檔案,裡面只負責Synthsize所有的屬性。

#import 
#import "object.h"

@implementation RootObject
@synthesize Id,first_name,gender,last_name,locale,name,username;
@end

 

接下來的任務就是怎麼把JSON檔案對應到一個物件集合,對應的方法你可以捲起袖子自己來。

當然做起來就會比較辛苦一點,像在Stackoverflow有許多相關的文章分享。沒有什麼特別的技巧,自己硬幹的話不外乎就是自己寫個函數,去把Json資料對應回一個物件集合。在.Net的環境下,我們就會可以使用泛型集合List<Object>來處理,不過Objective-c沒有List<object>這種使用法,Swift才有,所以在Objective-c就用NSMuTableArray來處理。

http://stackoverflow.com/questions/20374986/in-ios-how-do-i-parse-a-json-string-into-an-object

 

當然,懶惰的我們,自己硬幹太累了。當然是去找找有沒有現成更Smart的方法。

這邊就介紹Jastor這個物件,你可以到GitHub下載這個套件專案。

下載網址:https://github.com/elado/jastor

下載專案後,在你的專案加入下方四個檔案。分別是

Jastor.h,Jastor.m,JastorRuntimeHelper.h,JastorRuntimeHelper.m 這四個檔案。

 

這個Jastor 類別檔就是一開始在建立object.h檔案時候所繼承的Jastor類別。

@interface RootObject : Jastor

 

接下來看到主要程式,在從網路取得Json資料的格式與上一個章節一模模一樣樣,只多了呼叫下面的這一行,就可以把Json資料轉換成物件,使用物件屬性來操作,而並不是用NSDictionary<Key,Value>來操作。這樣強型別的概念就進來了。

RootObject *product = [[RootObject alloc] initWithDictionary:jsonobj];

 

main.m檔案完成程式碼如下:

#import 
#import "object.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSURL *url = [NSURL URLWithString:@"https://graph.facebook.com/benlu"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
            NSDictionary* jsonobj =
            [NSJSONSerialization JSONObjectWithData:data
                                            options:NSJSONReadingMutableContainers
                                              error:nil];

            RootObject *product = [[RootObject alloc] initWithDictionary:jsonobj];
            
            NSLog(@"%@",product.name);
           }
    return 0;
}

 

編譯執行這個程式,可以看到我們經由product.name的物件屬性方式取得了資料。

 

下一個章節再繼續來討論當你取回來的資料是一個集合,那又要如何呈現?

 

範例檔案下載:https://github.com/twbenlu/JsonToObjectiveC/tree/master

參考資訊

https://github.com/elado/jastor

In iOS, how do I parse a JSON string into an object

http://stackoverflow.com/questions/20374986/in-ios-how-do-i-parse-a-json-string-into-an-object