iosobjective-cjsonafnetworking-2

Parsing JSON read the various dictionaries


I'm new to json and I'm having some difficulties, I'm trying to parse the following json.

But I am not able to read the various dictionaries "projects".

[{"project": {
"id": 123,
"name": "Produce RestKit Sample Code",
"description": "We need more sample code!",
"user": {
    "id": 1,
    "name": "Blake Watters",
    "email": "blake@twotoasters.com"
},
"tasks": [
    {"id": 1, "name": "Identify samples to write", "assigned_user_id": 1},
    {"id": 2, "name": "Write the code", "assigned_user_id": 1},
    {"id": 3, "name": "Push to Github", "assigned_user_id": 1},
    {"id": 4, "name": "Update the mailing list", "assigned_user_id": 1}
]}},
{"project": {
"id": 456,
"name": "Document Object Mapper",
"description": "The object mapper could really use some docs!",
"user": {
    "id": 2,
    "name": "Jeremy Ellison",
    "email": "jeremy@twotoasters.com"
},
"tasks": [
    {"id": 5, "name": "Mark up methods with Doxygen markup", "assigned_user_id": 2},
    {"id": 6, "name": "Generate docs and review formatting", "assigned_user_id": 2},
    {"id": 7, "name": "Review docs for accuracy and completeness", "assigned_user_id": 1},
    {"id": 8, "name": "Publish to Github", "assigned_user_id": 2}
]}}]

I'm using AFNETWorking and this is my code:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
for (NSDictionary *json in [responseObject objectForKey:@"project"]){
        simProjects *proj = [[simProjects alloc] init];
        proj.description = [json objectForKey: @"description"];

Solution

  • As was noted, you do have an array of dictionaries. You want:

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *projects = responseObject;
        for (NSDictionary *data in projects) {
            NSDictionary *project = data[@"project"];
            simProjects *proj = [[simProjects alloc] init];
            proj.description = project[@"description"];
        }
    }