2012-05-05 113 views
1

我設法讓Json的爲我的服務器,並在Xcode分析,然後我可以轉換JSON來一個對象,並載入我的UITableView,問題是我的Json有7個對象..Xcode中如何解析JSON對象

你可以看到full Json here

2012-05-05 10:45:02.727 passingdata[63856:fb03] array : { 
    posts =  { 
     Friday =   (
         { 
       GymClass =     { 
        "CLASS-TYPE2" = ""; 
        "CLASS_LEVEL" = "Intro/General"; 
        "CLASS_TYPE" = "Muay Thai"; 
        "DAY_OF_WEEK" = Friday; 
        TIME = "13:00 - 14:30"; 
       }; 
      } 
     ); 
     Monday =   (
         { 
       GymClass =     { 
        "CLASS-TYPE2" = "Fighters Training"; 
        "CLASS_LEVEL" = "Fighters/Advanced/Intermediate"; 
        "CLASS_TYPE" = "Muay Thai "; 
        "DAY_OF_WEEK" = Monday; 
        TIME = "09:30 - 11:00"; 
       }; 
      }, ...... 

與此代碼,我可以得到上週五的「星期五」,並在我的桌子

- (void)fetchedData:(NSData *)responseData { //parse out the json data 

    searchResults2 = [NSMutableArray arrayWithCapacity:10]; 

    NSError* error; 
    NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; 

    NSLog(@"array : %@",dictionary); 
    NSArray *array = [[dictionary objectForKey:@"posts"] objectForKey:@"Friday"]; // retrieve that Day Gym Classes 

    if (array == nil) { 
     NSLog(@"Expected 'posts' array"); 
     return; 
      } 

    for (NSDictionary *resultDict in array) 
    { 
     SearchResult *searchResult3; 
     searchResult3 = [self parseTrack:resultDict]; 

     if (searchResult3 != nil) { 
      [searchResults2 addObject:searchResult3]; 
     }   
    }  
    [self.tableView reloadData]; 
} 

- (SearchResult *)parseTrack:(NSDictionary *)dictionary 
{ 
    SearchResult *searchResult1 = [[SearchResult alloc] init]; 

    searchResult1.classType= [[dictionary objectForKey:@"GymClass"] objectForKey:@"CLASS_TYPE"]; 
    searchResult1.classLevel= [[dictionary objectForKey:@"GymClass"] objectForKey:@"CLASS_LEVEL"]; 

    NSLog(@"parse track = %@", searchResult1); 
    return searchResult1; 
} 

我能得到的Elemen顯示GymClass信息「GymClass」 ts一天,但我怎樣才能得到元素的每一天(星期一,星期二...太陽),所以我可以分段顯示在我的桌子上?

感謝您的幫助..

在你的代碼

回答

8

好,我們已經在做的是:

NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; 

NSLog(@"array : %@",dictionary); 
NSArray *array = [[dictionary objectForKey:@"posts"] objectForKey:@"Friday"]; // retrieve that Day Gym Classes 

文可以從那裏開始只檢索對象posts

NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; 
NSDictionary *posts = [dictionary objectForKey:@"posts"]; 

//Iterate over posts 

for (NSArray *aDay in posts){ 
    //Do something 
    NSLog(@"Array: %@", aDay); 
} 

在這裏,我使用快速枚舉遍歷字典,你應該檢查這個here

+0

嗨我知道如何獲得一天的信息「星期五」,我只是不知道如何得到所有天的信息.. – HernandoZ

+0

@HernandoZ看看第二塊代碼。我沒有使用'Friday',只遍歷所有 –

+0

非常感謝,所以如果我使用快速枚舉,我需要做什麼?每天保存到NSArray?那麼我會有7個陣列來收集信息? ,很抱歉是一個痛苦,你可以解釋我應該遵循什麼過程來獲得一天中的所有天信息按天節排序,我知道如何做一個數組,我爲「星期五」,但使用多個數組?感謝您的幫助.. – HernandoZ