如何访问NSMutableArray中的JSON数据? [英] How do I access JSON data in an NSMutableArray?
问题描述
我正在尝试访问从网站获取并存储在数组中的JSON数据.但是,首先,我想过滤掉除
valueForKey:
方法所做的.为了测试这一点,我使用NSLog
方法将它们写入日志,但是当我运行它时却得到"null".
I'm trying to access JSON data that I have taken from a website and stored in an array. First, however, I want to filter out everything but the "title" information, which I am doing using the valueForKey:
method. In order to test this I am writing them to the log using the NSLog
method, however when I run this I get "null".
有人能告诉我为什么我得到我得到的东西吗?
Can anyone advise me, as to why I'm getting what I'm getting?
非常感谢您的帮助.
{
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);
}
推荐答案
查看在该pastebin中返回的JSON对象,您将得到以下信息:
Looking at the JSON object returned in that pastebin, you get the following:
{
"kind":"Listing",
"data":{
"modhash":"",
"children":[ ... ],
"after":"t3_1qwcm7",
"before":null
}
}
这不是数组,它是一个JSON对象.要获取子项的标题,您需要执行以下操作:
That is not an array, its a JSON object.. To get the titles of the children you would want to do the following:
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSMutableArray *children = [[json objectForKey:@"data"] objectForKey:@"children"];
NSMutableArray *titles = [children valueForKeyPath:@"data.title"];
这是因为子数组嵌套在"data"
对象中,而每个子对象嵌套在另一个"data"
对象中.
This is because the children array is nested in a "data"
object and each individual child object is nested in another "data"
object.
然后,您还需要调用valueForKeyPath:
而不是valueForKey:
,因为数据嵌套在另一个对象中
You then also need to call valueForKeyPath:
instead of valueForKey:
because the data is nested in another object
这篇关于如何访问NSMutableArray中的JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!