JSON and 2D array



以下是来自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/图像/线程/标题),并将其存储为一个类的实例。但是,我不知道如何访问二维数组中的每个对象。下面是我写的代码来测试我是否可以访问它们,但是它不起作用。

有什么问题吗?

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!!

在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
}

你给了我一个检查iOS 5原生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" = " Uc774Uc81c Uc571 Uac1cUbc1c Uc2dcUc791Ud574Ub3c4 Ub420Uac70 Uac19Uc740Ub370? ";
  //        "news_title" = "Ub418Ub294Uac70 Uac19Uc9c0?";
  //    }
  //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
}

相关内容

  • 没有找到相关文章

最新更新