【问题标题】:How do I access JSON data in an NSMutableArray?如何访问 NSMutableArray 中的 JSON 数据?
【发布时间】:2013-11-19 11:38:13
【问题描述】:

我正在尝试访问从网站获取并存储在数组中的 JSON 数据。但是,首先,我想过滤除“标题”信息之外的所有内容,我正在使用valueForKey: 方法进行此操作。为了测试这一点,我使用NSLog 方法将它们写入日志,但是当我运行它时,我得到“null”。

谁能告诉我,为什么我会得到我正在得到的东西?

感谢您的帮助,非常感谢。

{
    NSURL *redditURL = [NSURL URLWithString:@"http://pastebin.com/raw.php?i=FHJVZ4b7"];
    NSError *error = nil;
    NSString *jsonString = [NSString stringWithContentsOfURL:redditURL encoding:NSASCIIStringEncoding error:&error];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    NSMutableArray *titles = [json valueForKey:@"title"];
    NSLog(@"%@", json);

}

【问题讨论】:

  • jsonStringjson 数组打印到控制台(通过NSLog)。这应该让您知道出了什么问题。大概是来自 URL 的响应不是数组而是字典。
  • 为什么你把数据放到array它应该放到dictionary
  • NSMutableArray *children = [[json valueForKey:@"data"] valueForKey:@"children"]; NSMutableArray *titles = [children valueForKeyPath:@"data.title"];

标签: ios json macos nsmutablearray nsjsonserialization


【解决方案1】:

查看该 pastebin 中返回的 JSON 对象,您会得到以下信息:

    {
        "kind":"Listing",
        "data":{
        "modhash":"",
        "children":[ ... ],
        "after":"t3_1qwcm7",
        "before":null
        }
    }

这不是一个数组,它是一个 JSON 对象。要获取孩子的标题,您需要执行以下操作:

    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    NSMutableArray *children = [[json objectForKey:@"data"] objectForKey:@"children"];
    NSMutableArray *titles = [children valueForKeyPath:@"data.title"];

这是因为 children 数组嵌套在 "data" 对象中,而每个单独的子对象都嵌套在另一个 "data" 对象中。

然后您还需要调用valueForKeyPath: 而不是valueForKey:,因为数据嵌套在另一个对象中

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多