如何将这样的JSON解析为NSDictionary并获取键和值

时间:2014-03-22 03:02:15

标签: ios objective-c json nsdictionary

[
 {
"week": "1-16",
"course": "math",
"lecturer:": "AAA",
"credit": "2"   },
{
"week": "9-16",
"course": "tech",
"lecturer:": "BBB",
"credit": "2"   },
{
"week": "1-8",
"course": "English",
"lecturer:": "CC",
"credit": "0.5"   },
{
"week": "1-16",
"course": "German",
"lecturer:": "DDD",
"credit": "4"   }
]

我有这样一个JSON,我使用以下代码将其解析为NSDictionary

NSDictionary *resultDic = [NSJSerialization JSONObjectWithData:resData         options:NSJSONReadingAllowFragments error:nil];

但是当我尝试从NSDictionary的键中获取值时,会发生错误 我发现NSDictionary没有关键。

那么如何使用ObjectForKey获取值 感谢

1 个答案:

答案 0 :(得分:2)

resultDic将是一个字典数组,而不是字典本身。你想要这样的东西:

NSArray * resultArray = [NSJSONerialization JSONObjectWithData:resData   options:NSJSONReadingAllowFragments error:nil];
NSDictionary * result = [resultArray objectAtIndex:0];
NSString * week = [result objectForKey:@"week"];