Xcode如何解析Json Objects

时间:2012-05-05 10:11:27

标签: xcode json uitableview ios5

我设法为我的服务器获取Json并在Xcode中解析,然后我可以将Json转换为对象并加载我的uitableview,问题是我的Json有7个对象..

您可以看到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";
                };
            }, ......

使用此代码我可以获得星期五的“星期五”并在我的桌子上显示GymClass信息“GymClass”

- (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;
}

我可以获得一天的元素,但我如何获得每天的元素(星期一,星期二......太阳),所以我可以在我的桌子上按部分显示?

感谢您的帮助..

1 个答案:

答案 0 :(得分: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

Wen可以从那里开始只检索对象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