Simon Lee
Simon Lee

Reputation: 170

Parsing JSON with Objective-C

For my project I have built my own api using PHP. The result of json encoding basically gives me an array of entries like below

{"terms":[
           {"term0":
               {"content":"test id",
                "userid":"100","translateto":null,
                "hastranslation":"0",
                "created":"2011-10-19 16:54:57",
                "updated":"2011-10-19 16:55:58"}
               },
           {"term1":
               {"content":"Initial content",
                "userid":"3","translateto":null,
                "hastranslation":"0",
                "created":"2011-10-19 16:51:33",
                "updated":"2011-10-19 16:51:33"
               }
           }
         ]
}

However, I've been having problems working with NSMutableDictionary and extracting "content" in Objective-C.

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSMutableDictionary *JSONval = [responseString JSONValue];
[responseString release];

if (JSONval != nil) {
    NSMutableDictionary *responseDataDict = [JSONval objectForKey:@"terms"];
    if (responseDataDict!= nil) {
        for (id key in responseDataDict) {
            NSString *content = [[responseDataDict objectForKey:key]objectForKey:@"content"];
            [terms addObject:content];
            textView.text = [textView.text stringByAppendingFormat:@"\n%@", content];
        } 
        button.enabled = YES;
    }
}

}

Where NSLog spits out error when I send objectForKey to responseDataDict, which is a __NSArrayM according to the log.

What did I do wrong here?

Upvotes: 1

Views: 311

Answers (2)

user557219
user557219

Reputation:

NSMutableDictionary *responseDataDict = [JSONval objectForKey:@"terms"];

But the value of "terms" isn’t a dictionary; it’s an array. Note the square brackets in your JSON string. You should use:

NSArray *terms = [JSONval objectForKey:@"terms"];

instead.

Note that each term in the array is an object (a dictionary) containing a single name (key) whose corresponding value (object) is, in turn, another object (dictionary). You should parse them as:

// JSONval is a dictionary containing a single key called 'terms'
NSArray *terms = [JSONval objectForKey:@"terms"];

// Each element in the array is a dictionary with a single key
// representing a term identifier
for (NSDictionary *termId in terms) {
    // Get the single dictionary in each termId dictionary
    NSArray *values = [termId allValues];

    // Make sure there's exactly one dictionary inside termId
    if ([values count] == 1) {
        // Get the single dictionary inside termId
        NSDictionary *term = [values objectAtIndex:0];

        NSString *content = [term objectForKey:@"content"]
        …
    }
}

Add further validation as needed.

Upvotes: 1

Related Questions