Will Will - 5 months ago 18
iOS Question

Single object json parse - what am I doing wrong?

This has got to be something obvious that I am doing wrong. I have been banging my head against a wall trying to figure out what is going on. I already have this json parsing done in the android version of my app, now trying to parse this simple json in xcode and can't get it done.

NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
NSLog([res objectForKey:@"Date"]);


This code get me the "unrecognized selector sent to instance" error.

Here is the json data and you can see Date is one of the objects:

[{"Date":"2016-06-17T22:56:33.0811255-05:00"}]


Thanks in advance for any help on this issue. I've tried to simplify this post, but if more info is needed I will try and quickly provide.

http://i.stack.imgur.com/Y5fsT.png

Answer

JSONObjectWithData is returning an array of dictionaries (in this case a single dictionary) and not a dictionary. Your print out of the raw JSON confirms this:

[{"Date":"2016-06-17T22:56:33.0811255-05:00"}] // This is an array

However you're attempting to treat that response object like a dictionary. In doing so you're calling a dictionary method (objectForKey:) on an array. This results in a crash. Try something like this:

NSError *error = nil;
id responseObject = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error];  

if (error) 
{
    // Handle error

    return;
}

NSLog(responseObject); 

if ([responseObject isKindOfClass:[NSArray class]]) 
{
    NSArray *responseArray = (NSArray *)responseObject;
    for (id item in responseArray)
    {
        NSLog(item); 

        if ([item isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *dictionary = (NSDictionary *)item;
            NSString *dateString = [dictionary objectForKey:@"Date"];
            NSLog(dateString);
        }
    }
}
else 
{
    // responseObject is not an array...
}
Comments