2011-05-08 114 views
0

我需要將JSON字符串反序列化爲自定義複雜對象。將NSDictionary對象轉換爲自定義複雜對象

例如可以說我有JSON字符串:

{"Menu": { 
"categoryList": { 
"Category": [ 
{"name": "Cat1"}, 
{"name": "Cat1"}, 
{"name": "Cat3"} 
] 
} 
}} 

我如何反序列化這個字符串初始化具有所屬分類包括類型類別類3類對象菜單對象?有什麼辦法可以做到這一點?

回答

-1

嘗試使用JSON解析器。

http://code.google.com/p/json-framework/

它會分析你的字符串,並退給你,表示你的數據一個NSObject(NSArray的NSDictionary的或)。

編輯:

那麼,作爲OP希望得到一個自定義對象,而不是一個NSDictionary/NSArray的,它可以實現的東西,如下(假設做太困難會得到正確的數據,並設置每個新對象的屬性)

基礎上code provided by @andrewsardone,人們可以利用志願來獲得與相應地設置屬性的新對象,處理JSON與任何解決方案解析後容易實現的功能適合您的項目更好地

+(id) objectFromDictionary:(NSDictionary *)dict { 

    id entry = [[self alloc] init]; 

    Class aClass = [entry class]; 

    do { 

     unsigned int outCount, i; 
     objc_property_t *properties = class_copyPropertyList(aClass, &outCount); 
     for (i = 0; i < outCount; i++) { 
      objc_property_t property = properties[i]; 
      NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding] autorelease]; 
      id propertyValue = [dict objectForKey:propertyName]; 
      if (propertyValue && ![propertyValue isEqual:[NSNull null]]) { 
       [entry setValue:propertyValue forKey:propertyName]; 
      } 
     } 

     free(properties); 

     //added to take care of the class inheritance 
     aClass = [aClass superclass]; 

    } while (![[[aClass class] description] isEqualToString:[NSObject description]]); 

    return [entry autorelease]; 
} 
+1

nsarray和nsdictionary不是自定義對象 – 2012-12-19 03:40:43

+0

@rocity所以,我最後的編輯添加了自定義對象的解決方案,這似乎是OP正在尋找 – 2013-01-21 12:27:35

0

這是一個所需的功能,似乎沒有一個好的(公共)解決方案。