Convert JSON feed to NSDictionary

linkingarts picture linkingarts · Feb 18, 2011 · Viewed 72.8k times · Source

Where JSON_CATEGORY_DATA_URL_STRING is my feed URL, which returns fine as:

[
    {
        "group":"For Sale",
        "code":"SSSS"
    },
    {
        "group":"For Sale",
        "category":"Wanted",
        "code":"SWNT"
    }
]

I cannot seem to get a nice NSDictionary (or NSArray) out of the following code:

+ (NSDictionary *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *json_dict = (NSDictionary *)json_string;
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_string;
}

I've read many posts on this, but am not getting it.

Answer

lagos picture lagos · Mar 20, 2012

With IOS5 you can use NSJSONSerialization for serializing the JSON.

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