Reputation: 21
I have this JSON:
{
"errors": [
],
"warnings": [
],
"data": {
"token": "someToken"
},
"page": {
"current": 1,
"total": 1
}
}
I am trying to parse token with SBJSON. There is no problem parsing it. But, in some cases there retrieved JSON has no token value. How do I check if the value exists or not, because if i do no check my app crashes with EXCBadAccess.
Thanks!
Upvotes: 2
Views: 1421
Reputation: 42522
SBJSON will give you back a NSDictionary object. You just need to check if the pointer returned by objectForKey is nil, also check if it is NSNull (which will be the case if the value is present, but set to null in the JSON) and you can also make sure the data is actually a NSDictionary:
id dataDictionaryId = [resultsDictionary objectForKey:@"data"];
// check that it isn't null ... this will be the case if the
// data key value pair is not present in the JSON
if (!dataDictionaryId)
{
// no data .. do something else
return;
}
// then you need to check for the case where the data key is in the JSON
// but set to null. This will return you a valid NSNull object. You just need
// ask the id that you got back what class it is and compare it to NSNull
if ([dataDictionaryId isKindOfClass:[NSNull class]])
{
// no data .. do something else
return;
}
// you can even check to make sure it is actually a dictionary
if (![dataDictionaryId isKindOfClass:[NSDictionary class]])
{
// you got a data thing, but it isn't a dictionary?
return;
}
// yay ... it is a dictionary
NSDictionary * dataDictionary = (NSDictionary*)dataDictionaryId;
// similarly here you could check to make sure that the token exists, is not null
// and is actually a NSString ... but for this snippet, lets assume it is
NSString * token = [dataDictionary objectForKey:@"token"];
if (!token)
// no token ... do something else
Update
This is the test code I wrote to check the SBJSON parsing results:
NSError* error = NULL;
id json = [parser objectWithString:@"{\"data\":null}" error:&error];
NSDictionary * results = (NSDictionary*)json;
id dataDictionaryId = [results objectForKey:@"data"];
if (!dataDictionaryId || [dataDictionaryId isKindOfClass:[NSNull class]])
return NO;
Upvotes: 2
Reputation: 11543
Try to print out what's inside dataDictionary when there's no token.
Peraphs it's not nil.
You can check isKindOfClass(NSDictionary), instead of just put !dataDictionary.
Upvotes: 0