1

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. :)

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would add to the if condition && [key objectForKey:@"staff_id"] just in case since returned JSON seems unconsistent
@NickCatib fixed, DevC that's great :) , if it fixed the problem, please mark it correct for further readers.
@l0gg3r had to wait a few mins before I could accept according to SO, but all working thank you :)
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.