2014-02-18 108 views
1

我正在從服務器以下響應iOS來解析JSON?

[{"id":"16","name":"Bob","age":"37"},{"id":"17","name":"rob","age":"28"}]; 

我使用它AFNetworking框架,

我得到在NSData上述反應,然後用下面的代碼,我能收集到在NSDictionary

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error]; 

但如何將數據解析從NSDictionary"name""age"價值?

+0

你也可以使用這種格式過於'[字典objectForKey:@「名」];' – Rugmangathan

回答

5

您預期的NSDictionary,但你的回答給你的字典數組,試試這個:

NSArray *array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error]; 
for (NSDictionary *dict in array) 
{ 
    NSLog(@"Name: %@, age: %@", dict[@"name"], dict[@"age"]); 
} 

//擴展

從註釋下,它看起來像你必須從響應,而不是NSArray的字符串正如你在上面的代碼中顯示的那樣。 您可以解析字符串來得到你想要的數據,或者你可以將其轉換回JSON和NSArray的:

NSString * jsonString = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error]; 
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
    //As I post above 

現在你應該有一個NSArray和我的代碼應該做的工作。

+0

我已經試過,但與下面的錯誤消息 應用程序崩潰「[__NSCFString countByEnumeratingWithState:對象:伯爵:]」 –

+0

這不是NSArray bcoz m試圖使用計數功能.....但該應用程序崩潰 [__NSCFString計數]: 所以我認爲它不是NSArray –

+0

這個錯誤說,它不是一個數組,但NSString對象。但是你顯示的代碼說清楚那是NSArray。你可以調用:id data = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error]; NSLog(@「CLASS:%@」,NSStringFromClass([data class]);並讓我知道輸出是什麼 – Greg