DevC
DevC

Reputation: 7022

How to check if JSON object contains values

I have a JSON array that I parse. I parse the values from the key Staff, however sometimes the Staff object contain no values;

Expected return;

enter image description here

But sometimes it returns:

enter image description here

Which causes the app to crash because key[@"staff"][@"staff_id"] doesnt exist.

Ive tried:

if (key[@"staff"][@"staff_id"]){
     //Parse staff 
}
else{

    //staff is empty

}

But this crashes as well because I think it still looks for the [@"staff_id"] which doesnt exist.

I've also tried

if (![key[@"staff"][@"staff_id"] isKindOfClass:[NSNull class]])

And

if (![key[@"staff"] isKindOfClass:[NSNull class]])

Any help is greatly appreciated. :)

Upvotes: 1

Views: 811

Answers (2)

gnasher729
gnasher729

Reputation: 52538

You will only get object of class NSNull if the JSON contained a null value. For example a dictionary { "key": null } will contain a key/value pair with a key "key" and a value [NSNull null]. Instead of using "isKindOfClass" you can compare with [NSNull null], because there is only ever one NSNull object. If your JSON doesn't contain null values, that won't happen.

If your JSON sometimes contains a dictionary, and sometimes an array, well that's tough. Blame the guys creating the JSON. You can write for example:

id keyObject = ...; 
NSDictionary* keyDictionary = keyObject; 
NSArray* keyArray = keyArray; 

if ([keyDictionary isKindOfClass:[NSDictionary class]]) {
    .. you've got a dictionary
} else if ([keyArray isKindOfClass [NSArray class]]) { 
    .. you've got an array 
} else if (keyObject == nil) {
    .. there wasn't actually any key object
} else if (keyObject == [NSNull null]) { 
    .. your JSON contained "key": null
} else {
    .. your JSON contained a string, number, or boolean value
}

Upvotes: 0

l0gg3r
l0gg3r

Reputation: 8954

That's a great example of shitty backend.
On the first example enter image description here staff is a Dictionary, on the second example enter image description here is an Array.

You need to ask your backend developer, to decide and always return either Array, or Dictionary.

BTW, you can workaround it

if ([key[@"staff"] isKindOfClass:[NSDictionary class]] && key[@"staff"][@"staff_id"]) {
    id staffId = key[@"staff"][@"staff_id"];
} else {
    // Staff is empty
}

Upvotes: 2

Related Questions