【问题标题】:How to parse such a JSON to NSDictionary and get the keys and values如何将这样的 JSON 解析为 NSDictionary 并获取键和值
【发布时间】:2014-03-22 03:02:14
【问题描述】:
[
 {
"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 获取值 谢谢

【问题讨论】:

  • 访问 json.org 并研究 JSON 语法。 (只需要5-10分钟。)然后你会看到你拥有的是一个包含“对象”(字典)的数组。
  • 它是“NSJSONSerialization”,而不是“NSJSerialization”。

标签: ios objective-c json nsdictionary


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多