2011-11-20 9 views
1

다음은 PHP 웹 페이지에서 인코딩 된 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... 
} 

나는 정보 (날짜/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