I have a JSON that is a structured as an array of dictionaries.
The normal structure would be something like, (after parsing into array):
[0] - [NSDictionary *] 3 key/value pairs
[0] departure - 1 element
-> key @"city"
-> value @"New York"
[1] arrival -1 element
-> key @"city"
-> value @"Atlanta"
[2] bus -3 key/values pairs
-> key @"bus"
-> value (NSDictionary *) 3 key/value pairs
[0] @"number" (long) 123
[1] @"driver" @"smith"
[2] @"type" @"40 seat coach"
However, if you parse a "bad" JSON that has the structure but one of the key elements is missing (ie last element)
[0] - [NSDictionary *] 3 key/value pairs
[0] departure - 1 element
-> key @"city"
-> value @"New York"
[1] arrival -1 element
-> key @"city"
-> value @"Atlanta"
[2] bus -3 key/values pairs
-> key @"bus"
-> value (NSNull *) 0x8976656
-> NSObject
If I try to query the driver's name under bus it crashes. I've tried to test for the null but doesn't work. It doesn't throw an error during the request either (NSURLSessionDataTask). How do you guard against this?
NSArray *busCompany = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
myBuses =[[NSMutableDictionary]alloc]init];
for (NSDictionary *companiesDict in busCompany) {
myBuses = companiesDict[@"bus"];
if(myBuses) { //also tried if(myBuses != NULL)
NSString *driverName = [myBuses ForKey: @"driver"];
}
}
It gives me [NSNULL objectforkey]
error.