【问题标题】:Cannot extract data from NSDictionary filled with JSON Data无法从填充有 JSON 数据的 NSDictionary 中提取数据
【发布时间】:2012-03-16 10:54:04
【问题描述】:

我刚刚开始为 IOS5 编写应用程序。我目前有一个 PHP 网络服务,应用程序调用它来从数据库中检索数据。在数据库中,我现在有 3 行,当我进入调试器时,字典有 3 个键/值对。我无法检索任何值。我的代码如下:

NSURL *myUrl = [[NSURL alloc]initWithString:@"http://localhost/~stephen-hill9/index.php"];
NSData *data = [[NSData alloc] initWithContentsOfURL:myUrl];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"Parsed Data: %@", json);
NSDictionary *bodyDictionary = [json objectForKey:@"Product_Desc"]; <-APP CRASHES HERE - INVALID KEY
NSLog(@"Parsed Data: %@", bodyDictionary);

此外,这是我从调试器获得的字典包含的数据:

Parsed Data: (
        {
        0 = 1;
        1 = "Caromax 20HN B/F";
        2 = 51533;
        3 = 6650;
        4 = 1117760;
        5 = 1067224;
        6 = 1759741;
        7 = 1;
        8 = "0000-00-00 00:00:00";
        ID = 1;
        "Max_Volume" = 1759741;
        "Product_Code" = 51533;
        "Product_Desc" = "Caromax 20HN B/F";
        Pumpable = 1067224;
        Status = 1;
        "Tank_Level" = 6650;
        Updated = "0000-00-00 00:00:00";
        Volume = 1117760;
    },
        {
        0 = 2;
        1 = "C1 Kerosine";
        2 = 25101;
        3 = 1258;
        4 = 146871;
        5 = 111776;
        6 = 1018590;
        7 = 2;
        8 = "2023-02-12 20:00:00";
        ID = 2;
        "Max_Volume" = 1018590;
        "Product_Code" = 25101;
        "Product_Desc" = "C1 Kerosine";
        Pumpable = 111776;
        Status = 2;
        "Tank_Level" = 1258;
        Updated = "2023-02-12 20:00:00";
        Volume = 146871;
    },
        {
        0 = 3;
        1 = "Recovered Spirit";
        2 = 87902;
        3 = 6069;
        4 = 710172;
        5 = 675078;
        6 = 1018200;
        7 = 1;
        8 = "2012-03-16 00:00:00";
        ID = 3;
        "Max_Volume" = 1018200;
        "Product_Code" = 87902;
        "Product_Desc" = "Recovered Spirit";
        Pumpable = 675078;
        Status = 1;
        "Tank_Level" = 6069;
        Updated = "2012-03-16 00:00:00";
        Volume = 710172;
    }
)

我希望有人能够提供帮助 - 我确信问题一定是基本问题。

非常感谢,

斯蒂芬

【问题讨论】:

  • 如何从字典中提取数据?

标签: php json ios5


【解决方案1】:

好的,你在这里得到的是一个字典数组,而不是字典本身。 试试这个:

NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *bodyDictionary = [json objectAtIndex:0];

当然,这只会让你得到第一个对象,但你明白了......

【讨论】:

  • 感谢您的回答 - 我找不到 NSDictionary 的“objectAtIndex”方法:-S
  • 哎呀...道歉 - 我刚刚将第一个字典 - json 更改为一个数组并将 objectAtIndex 提取到第二个字典中,它已经工作了。非常感谢您的帮助!
  • 很高兴为您提供帮助 :) 如果您正在寻找答案,请考虑将答案设置为正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
  • 2020-05-31
  • 2020-12-18
  • 1970-01-01
相关资源
最近更新 更多