当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - check if NSdictionary - NESTED key is null

问题描述:

I am pulling json data ... and can't change how it comes out

(CASE 1) most times it comes out like this

collection1{

-paragraph {

href: "x",

text: "y"

},

title: "title"

},

(CASE 2)sometimes it comes out like this

paragraph: "y"

title: "title"

},

...

i do this -> NSString * paragraphText = [[postDictionary objectForKey:@"paragraph"] objectForKey:@"text"];

to get the data in CASE 1

but for case two i need to check if the NESTED key -> [[postDictionary objectForKey:@"paragraph"] objectForKey:@"text"]; exists

if it doesn't then just use -> [[postDictionary objectForKey:@"paragraph"]

i have tried so many ways to check if the key exists ... i.e

  1. id obj = [[postDictionary objectForKey:@"paragraph"] objectForKey:@"text"];

    if (obj == [NSNull null]) {

  2. if (![[postDictionary objectForKey:@"paragraph"] objectForKey:@"text"]) and other variations of the above ...

i get the error -> [__NSCFString objectForKey:]: unrecognized selector sent to instance 0x145731f0'

i know that the key does not exist ...

How do i check if a nested key exists? .. this way i can try another key access the data?

网友答案:

Check for the paragraph's type, if it's a dictionary it's case 1

id paragraph = postDictionary[@"paragraph"];
if([paragraph isMemberOfClass: [NSDictionary class]])
{
    // case 1
    NSString *textFromParagraph = ((NSDictionary*)paragraph)[@"text"];
}
网友答案:

Thanks Eike, Rishi and Adama. I ended up doing

NSDictionary * paragraph = postDictionary[@"paragraph"];

    if ([paragraph isKindOfClass:[NSDictionary class]])
    {[@"text"];
        blogPost.content    = [[postDictionary objectForKey:@"paragraph"]  objectForKey:@"text"];
    }else{
        blogPost.content    = [postDictionary objectForKey:@"paragraph"];
    }

I learnt something.

Thank you :D

分享给朋友:
您可能感兴趣的文章:
随机阅读: