如何到达JSON的复杂部分?

时间:2014-06-10 09:15:53

标签: ios objective-c json

这是我的JSON回复

{
error: false,
loggedin: null,
-data: {
    -homework: [
    -{
        +HomeworkSession: {},
        +elements: []
    },
    +{},
    {},
    {}
    ],
    +lessons: {},
    +date_span: {},
    +type: "parents"
    }
}

我无法弄清楚如何到达 HomeworkSession 。 我使用以下代码将它放入NSData中来获取此JSON:

_jsonData = [[NSData alloc] initWithContentsOfURL:
                  [NSURL URLWithString:@"my_url"]];

但是我不能从那里开始......无论我做什么,我都会得到零回应。 任何一段代码都会有所帮助!

1 个答案:

答案 0 :(得分:2)

代码应该是这样的: -

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
    NSDictionary * data = [jsonDictionary objectForKey:@"data"];
    NSArray * homework = [data objectForKey:@"homework"];

    for(int i=0;i<homework.count;i++){
        NSDictionary * singleHomework = [homework objectAtIndex:i];

        NSDictionary *HomeworkSession = [singleHomework objectForKey:@"HomeworkSession"];
        NSArray *elements = [singleHomework objectForKey:@"elements"];

        NSLog(@"%@",HomeworkSession);
        NSLog(@"%@",elements);
    }

注意:NSLog将显示nil为HomeworkSession,元素为空。