以下是来自PHP网页的编码JSON数据。
{
{
"news_date" = "2011-11-09";
"news_id" = 5;
"news_imageName" = "newsImage_111110_7633.jpg";
"news_thread" = "test1";
"news_title" = "test1 Title";
},
{
"news_date" = "2011-11-10";
"news_id" = 12;
"news_imageName" = "newsImage_111110_2060.jpg";
"news_thread" = "thread2";
"news_title" = "title2";
},
// and so on...
}
我想获取一个信息(日期/ id /图像/线程/标题),并将其存储为类的实例。但是,我不知道如何访问2D数组中的每个对象。 以下是我编写的代码,用于测试我是否可以访问它们,但它不起作用。
会出现什么问题?
NSURL *jsonURL = [NSURL URLWithString:@"http://www.sangminkim.com/UBCKISS/category/news/jsonNews.php"];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
SBJsonParser *parser = [[SBJsonParser alloc] init];
contentArray = [parser objectWithString:jsonData];
NSLog(@"array: %@", [[contentArray objectAtIndex:0] objectAtIndex:0]); // CRASH!!
答案 0 :(得分:3)
在JSON术语中,这不是一个二维数组:它是一个数组,其元素是对象。在Cocoa术语中,它是一个数组,其元素是字典。
您可以这样阅读:
NSArray *newsArray = [parser objectWithString:jsonData];
for (NSDictionary *newsItem in newsArray) {
NSString *newsDate = [newsItem objectForKey:@"news_date"];
NSUInteger newsId = [[newsItem objectForKey:@"news_id"] integerValue];
NSString *newsImageName = [newsItem objectForKey:@"news_imageName"];
NSString *newsThread = [newsItem objectForKey:@"news_thread"];
NSString *newsTitle = [newsItem objectForKey:@"news_title"];
// Do something with the data above
}
答案 1 :(得分:2)
你给了我一个机会来检查iOS 5 Native JSON解析器,所以不需要外部库,试试这个:
-(void)testJson
{
NSURL *jsonURL = [NSURL URLWithString:@"http://www.sangminkim.com/UBCKISS/category/news/jsonNews.php"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:jsonData //1
options:kNilOptions
error:&error];
NSLog(@"First Dictionary: %@", [json objectAtIndex:0]);
//Log output:
// First Dictionary: {
// "news_date" = "2011-11-09";
// "news_id" = 5;
// "news_imageName" = "newsImage_111110_7633.jpg";
// "news_thread" = " \Uc774\Uc81c \Uc571 \Uac1c\Ubc1c \Uc2dc\Uc791\Ud574\Ub3c4 \Ub420\Uac70 \Uac19\Uc740\Ub370? ";
// "news_title" = "\Ub418\Ub294\Uac70 \Uac19\Uc9c0?";
// }
//Each item parsed is an NSDictionary
NSDictionary* item1 = [json objectAtIndex:0];
NSLog(@"Item1.news_date= %@", [item1 objectForKey:@"news_date"]);
//Log output: Item1.news_date= 2011-11-09
}