2012-01-05 91 views
0

我有一個JSON提要這樣的:迭代通過嵌套的JSON數組iPhone

{ 
result = { 
    cars = { 
     brand = { 
      fields = { 
     name = { 
     id = 1234; 
         value = "Opel Astra"; 
      }; 
    description = { 
     id = 4432; 
     value = "Some description"; 
    }; 
      }; 
     fields = { 
     name = { 
     id = 1453; 
         value = "Opel Omega"; 
      }; 
    description = { 
     id = 4430; 
     value = "Some description"; 
    }; 
    ... 
      }; 
    }; 
    }; 

當我分析這一點,我得到了一個數組,而不是作爲一個單獨的字符串,這是我想要的所有對象。

我做這樣的:

NSArray *result = [[res objectForKey:@"result"]valueForKeyPath:@"cars.brand.fields.name.value"]; 
NSLog(@"%@" , [result objectAtIndex:0]): 

輸出是:

(
    "Opel Astra", 
    "Opel Omega", 
    .... 
), 

我怎樣才能做到讓一個字符串的時間,而不是包含了很多字符串數組?

謝謝!

回答

0

使用NSJSONSerialization將JSON數據檢索到基礎對象中。

另請參閱此post

+0

無法使用NSJSONSerialization,因爲它僅適用於iOS 5.0及更高版本。 – Magnus 2012-01-05 09:19:02

0

的SBJSON你也能夠處理JSON字符串作爲ID的價值。 然後你調用[jsonString objectForKey:@「result」]。

並嘗試這個功能,它完美對我來說)

- (id) objectInObject:(NSObject *) rootObject forPath:(NSString *) aKeyPath { 

NSArray *keys = [aKeyPath componentsSeparatedByString:@"."]; 
NSObject *anObject = rootObject; 


for (NSString *aKey in keys) { 
    int arrayIndex = 0; 
    bool isArray = NO; 

    // check array 
    if ([[aKey substringToIndex:2] isEqualToString:@"i:"]) { 
     isArray = YES; 
     NSArray *values = [aKey componentsSeparatedByString:@":" ]; 
     arrayIndex = [[values objectAtIndex:1] intValue]; 
    } 

    if (isArray) { 
     anObject = [(NSArray *) anObject objectAtIndex:arrayIndex]; 
    } else { 
     anObject = [(NSDictionary *) anObject objectForKey:aKey]; 
    } 
} 
return anObject; 

}

+0

我應該只是傳遞一個數組或字典,爲rootObject? – Magnus 2012-01-05 09:42:15

+0

我試過這種方法。我通過了一個NSArray。仍然得到相同的輸出 – Magnus 2012-01-05 09:49:29

+0

什麼是「我:」?你從哪裏得到? – Magnus 2012-01-05 09:51:25

0

使用SBJson爲您的JSON庫。然後使用這一行代碼(響應是一個字符串),你會得到你想要的輸出。

NSMutableDictionary *responseJSON = [response JSONValue];