2011-11-20 38 views
1

以下は、PHPのWebページからエンコードされたJSONデータです。JSONと2D配列

{ 
    { 
     "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... 
} 

Iは、情報(日付/ ID /画像/スレッド/タイトル)のブーフをつかみ、そしてクラスのインスタンスとして格納したいです。しかし、私は2D配列の各オブジェクトにアクセスする方法には手がかりがありません。 以下は、私がそれらにアクセスできるかどうかをテストするために書いたコードですが、動作しません。

どのような問題がありますか?

答えて

3

JSONの用語では、これは2次元配列ではありません。要素がオブジェクトである配列です。 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 
} 
+0

を私は全くのことを考えました2d配列のように見えます。どうもありがとうございました!! :) – Raccoon

2

あなたは私の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" = " \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 
} 
+0

ありがとうございました:D – Raccoon