Подтвердить что ты не робот

Как я могу проверить Если я получил null от json?

Здесь я получил от JSON

[{ "фото": нулевой}]

и я использую этот код

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

Как я могу проверить его, если я хочу использовать if()??

изменить

вот JSON Data​​p >

   [{"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"}]}
  ]

и вот мой парсер JSON

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];

Спасибо за помощь

4b9b3361

Ответ 1

Я считаю, что большинство парсеров JSON представляют null как [NSNull null].

Учитывая, что jsonDict указывает на тот единственный элемент в массиве, тогда должно работать следующее:

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

Изменить на основе комментария:, поэтому jsonDict, несмотря на его имя, является массивом. В этом случае переименуйте jsonDict в jsonArray, чтобы избежать дальнейшей путаницы. Затем, учитывая jsonArray, указывает на массив, аналогичный примеру, опубликованному в вопросе:

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

Дальнейшее редактирование на основе модифицированного вопроса OP:

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 an array
        NSArray *innerPhotos = photo;
        …
    }
}

Ответ 2

Макросы могут быть полезны, если полезная нагрузка является сложной структурой JSON, имеющей возможные значения.

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

и макрос можно ссылаться как

SET_IF_NOT_NULL(myRecord.name, [jsonData objectForKey:@"name"]);

Ответ 3

Нет простого способа справиться с этим, но способ, которым я это делаю, - сделать категорию в NSObject:

@interface NSObject (NotNull)

- (instancetype)notNull;

@end

Реализовано так:

@implementation NSObject (NotNull)

- (instancetype)notNull
{
    return self;
}

@end

@implementation NSNull (NotNull)

- (instancetype)notNull
{
    return nil;
}

@end

Затем вы можете отправить notNull на любой необязательный объект в JSON dict, и вы получите nil назад, если это NSNull. В противном случае вы получите исходный объект. Например:

self.parentIdentifier = [dictionary[@"parent_id"] notNull];

Ответ 4

попробуйте проверить [jPhoto count] или [NSNull null]

Ответ 5

Надеюсь, что это поможет.

- (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;

}