12

Here I got from JSON

[{"photo":null}]

and I use this code

NSMutableArray *jPhoto = [NSMutableArray arrayWithArray:(NSArray *)[jsonDict valueForKey:@"photo"]];

How can I check it if I want to use if() ??

edit

here is JSON Data

   [{"photo":
              [{"image":"http:\/\/www.yohyeh.com\/upload\/shisetsu\/13157\/photo\/1304928459.jpg","title":"test picture","content":"this is description for test picture.\r\n\u8aac\u660e\u6587\u306a\u306e\u306b\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb"}
              ,{"image":"http:\/\/www.yohyeh.com\/upload\/shisetsu\/13157\/photo\/1304928115.jpg","title":"nothing","content":"iMirai"}
              ,{"image":"http:\/\/www.yohyeh.com\/upload\/shisetsu\/13157\/photo\/1303276769.jpg","title":"iMirai","content":"Staff"}]}
  ]

and here is my JSON parser

NSError *theError = nil;     
    NSString *URL = [NSString stringWithFormat:@"http://www.yohyeh.com/apps/get_sub_detail.php?id=%@&menu=photo",g_id];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
    NSURLResponse *theResponse =[[[NSURLResponse alloc]init] autorelease];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];   
    NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSDictionary *jsonDict = [string JSONValue];

Thank for help

crazyoxygen
  • 706
  • 1
  • 11
  • 30
  • Which JSON parser are you using? –  May 19 '11 at 04:06
  • I use JSON-framework.And there are a lot attribute in photo,not just image link but many thing.I'm not sure that I'm correct.But I think NSMutable is okay. or not ??? please giude me. : ) – crazyoxygen May 19 '11 at 04:08
  • It’d help if you posted a more complete example of the JSON data as well as the code you’re using to parse them. –  May 19 '11 at 04:09
  • oh by this.If I use NSMutableArray.I can use this if([jPhoto objectAtIndex:0]== [NSNull null]) { } and It work. thank for many help. But I'm still waiting for Bavarious's guide. :) – crazyoxygen May 19 '11 at 04:28

5 Answers5

37

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;
        …
    }
}
  • Oh it crash.Here is an error -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x58938e0 2011-05-19 11:10:47.131 iLife[2012:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x58938e0' – crazyoxygen May 19 '11 at 04:11
  • This means that `jsonDict` is an array, not a dictionary. Please see my last comment on your question. –  May 19 '11 at 04:13
7

Macros can be helpful if payload is complex JSON structure having possible values.

#define SET_IF_NOT_NULL(TARGET, VAL) if(VAL != [NSNull null]) { TARGET = VAL; }

and macro can be referenced like

SET_IF_NOT_NULL(myRecord.name, [jsonData objectForKey:@"name"]);
Ramesh
  • 1,703
  • 18
  • 13
  • May i know what you mean by myrecord.name – btmanikandan Aug 18 '14 at 12:37
  • Very good solution, instead of creating categories for NSObject and excessive 'if' conditions. Vote up, @Ramesh – kokoko Mar 27 '15 at 11:06
  • Voted Up! I'm having error while trying to use this macro for parsing double values. `Invalid operands to binary expression ('double _Nullable' and 'NSNull * _Nonnull')` and `Invalid operands to binary expression ('double _Nullable' and 'void *')` How do I solve this? – LoveMeSomeFood Apr 04 '17 at 22:23
5

There's no easy way of dealing with this, but the way I do it is to make a category on NSObject:

@interface NSObject (NotNull)

- (instancetype)notNull;

@end

Implemented like so:

@implementation NSObject (NotNull)

- (instancetype)notNull
{
    return self;
}

@end

@implementation NSNull (NotNull)

- (instancetype)notNull
{
    return nil;
}

@end

Then you can send notNull to any optional object in a JSON dict and you'll get nil back if it's NSNull. Otherwise you get the original object. For example:

self.parentIdentifier = [dictionary[@"parent_id"] notNull];
joerick
  • 16,078
  • 4
  • 53
  • 57
  • Love it! I have just added a three letter prefix to the method name just to be extra safe :) – sloik Aug 17 '15 at 18:05
  • @joerick The solution is working but I didn't get the logic behind this. If possible can please explain its workflow that will be helpful. Thanks. – The iCoder Sep 11 '18 at 11:45
0

Hope so this helps.

-(NSMutableDictionary *)jsonCheckforNull:(NSMutableDictionary *)json{

NSMutableDictionary* strongjson=[json mutableCopy];

for (NSString *ktr in json) {

    NSObject *str=[json objectForKey:ktr];

    if ([str isKindOfClass:[NSArray class]]) {
        if (!(str==[NSNull null])) {
            NSArray *temp = [json allKeysForObject:str];
            str=[[self ArrayCheckforNull:(NSMutableArray*)str]mutableCopy];
            NSString *key = [temp objectAtIndex:0];
            [strongjson removeObjectForKey:key];
            [strongjson setObject:str forKey:key];
        }
        else
        {
            NSArray *temp = [strongjson allKeysForObject:str];
            NSString *key = [temp objectAtIndex:0];
            [strongjson removeObjectForKey:key];
            [strongjson setObject:@"-----" forKey:key];
        }

    }
    else if ([str isKindOfClass:[NSDictionary class]]) {
        if (!(str==[NSNull null])) {
            str=[[self jsonCheckforNull:str]mutableCopy];
            NSArray *temp = [strongjson allKeysForObject:str];
            NSString *key = [temp objectAtIndex:0];
            [strongjson removeObjectForKey:key];
            [strongjson setObject:str forKey:key];
        }
        else
        {
            NSArray *temp = [strongjson allKeysForObject:str];
            NSString *key = [temp objectAtIndex:0];
            [strongjson removeObjectForKey:key];
            [strongjson setObject:@"-----" forKey:key];
        }

    }

    else {

        if (str ==[NSNull null]) {
            NSArray *temp = [strongjson allKeysForObject:str];
            NSString *key = [temp objectAtIndex:0];
            [strongjson removeObjectForKey:key];
            [strongjson setObject:@"----" forKey:key];
        }

    }

}
return strongjson;

}

-(NSMutableArray *)ArrayCheckforNull:(NSMutableArray *)arr{

NSObject *str;
NSMutableArray* strongArray=[[[NSMutableArray alloc]initWithArray:arr]mutableCopy];
for (str in arr)
{

    if ([str isKindOfClass:[NSArray class]]) {
        if (!(str==[NSNull null])) {
            str=[[self ArrayCheckforNull:(NSMutableArray *)str]mutableCopy];
            [strongArray removeObjectAtIndex:0];
            [strongArray addObject:str];
        }
        else
        {
            [strongArray removeObject:str];
            [strongArray addObject:@"----"];

        }

    }
    else if ([str isKindOfClass:[NSDictionary class]]) {
        if (!(str==[NSNull null])) {
            str=[[self jsonCheckforNull:(NSMutableDictionary*)str]mutableCopy];
            [strongArray removeObjectAtIndex:0];
            [strongArray addObject:str];

        }
        else
        {
            [strongArray removeObject:str];
            [strongArray addObject:@"----"];
        }

    }

    else {

        if (str ==[NSNull null]) {
            [strongArray removeObject:str];
            [strongArray addObject:@"----"];
        }


    }

}
return strongArray;

}

dasCS
  • 151
  • 1
  • 8
0

try to check for [jPhoto count] or [NSNull null]

saadnib
  • 11,145
  • 2
  • 33
  • 54