How can I check If I got null from json?

后端 未结 5 981
孤独总比滥情好
孤独总比滥情好 2020-12-31 09:13

Here I got from JSON

[{\"photo\":null}]

and I use this code

NSMutableArray *jPhoto = [NSMutableArray arrayWithArray:(NSArray *)[jsonDict va         


        
5条回答
  •  不思量自难忘°
    2020-12-31 09:31

    I believe most JSON parsers represent null as [NSNull null].

    Considering jsonDict points to that single element in the array, then the following should work:

    if ([jsonDict objectForKey:@"photo"] == [NSNull null]) {
        // it's null
    }
    

    Edit based on comment: so jsonDict, despite its name, is an array. In that case, rename jsonDict to jsonArray to avoid further confusion. Then, considering jsonArray points to an array similar to the example posted in the question:

    NSArray *photos = [jsonArray valueForKey:@"photo"];
    for (id photo in photos) {
        if (photo == [NSNull null]) {
            // photo is null
        }
        else {
            // photo isn't null
        }
    }
    

    Further edit based on OP’s modified question:

    NSArray *jsonArray = [string JSONValue];
    
    NSArray *photos = [jsonArray valueForKey:@"photo"];
    for (id photo in photos) {
        if (photo == [NSNull null]) {
            // photo is null
        }
        else {
            // photo isn't null. It's an array
            NSArray *innerPhotos = photo;
            …
        }
    }
    

提交回复
热议问题