2011-04-23 74 views
2

我想創建一個將JSON字符串轉換爲對象的JSON庫。 什麼是最清潔的方式來標記與JSON字符串相關的屬性? 是否有可能實現的東西像下面的代碼目標C - 數據綁定?

注意:下面的代碼不能正常工作,它只是一個樣本,以顯示我想要實現

JSON字符串

{ 
    "FIRST_NAME": "Some first name", 
    "LAST_NAME": "Some last name" 
    "CLASSES" : 
    [ 
     { 
     "CLASS_NAME": "class 1" 
     } 
     { 
     "CLASS_NAME": "class 2" 
     } 
    ] 
} 

型號

@interFace Student 

[JSON = "FIRST_NAME"] 
@property (nonatomic, retain) NSString *firstName; 

[JSON = "LAST_NAME"] 
@property (nonatomic, retain) NSString *lastName; 

[JSON = "CLASSES"] 
@property (nonatomic, retain) NSArray *classes; 

@end 

JSON方法

@implementation JSON 
+ (id)getObjectFromJSONString:(NSString*)string withType:(Class)class 
{ 
    //Create a student Object 
    //for each property if there is a JSON mark look for the value in json string 
    //populate all available values 
    //return object 
} 
@end 

回答

2

這當然是可能的。但是請注意,Objective-C不支持可以在運行時檢查的任意源代碼註釋,所以JSON鍵和代表實例變量或聲明屬性的對象鍵之間的映射不會完全像您所描述的。我建議你看看RestKit。除了幫助您將程序連接到RESTful服務外,它還有一個對象映射基礎結構,可以以聲明方式將遠程JSON消息轉換爲本地域對象。

0

我假設你正在使用JSON-框架解析JSON。

據我所知。我們一直在編寫一些使用JSON輸入的數據客戶端。

根據誰維護REST服務,您還必須檢查NULL值等內容。你也可能需要將值轉換爲Integer/Float。

+0

是我計劃使用JSON框架解析JSON字符串的NSDictionary – aryaxt 2011-04-23 04:11:08