JSON Response iPhone App的非空验证

vir*_*ral 4 iphone json web-services objective-c

目前我使用以下方法来验证数据不是Null.

if ([[response objectForKey:@"field"] class] != [NSNull class])
    NSString *temp = [response objectForKey:@"field"];
else
    NSString *temp = @"";
Run Code Online (Sandbox Code Playgroud)

当响应字典包含数百个属性(和相应的值)时出现问题.我需要将这种条件添加到字典的每个元素中.

还有其他方法可以实现吗?

是否有任何对Web服务进行任何更改的建议(除了不将空值插入数据库)?

任何想法,任何人?

小智 7

我所做的是在NSDictionary上添加一个类别

@interface NSDictionary (CategoryName)

/**
 * Returns the object for the given key, if it is in the dictionary, else nil.
 * This is useful when using SBJSON, as that will return [NSNull null] if the value was 'null' in the parsed JSON.
 * @param The key to use
 * @return The object or, if the object was not set in the dictionary or was NSNull, nil
 */
- (id)objectOrNilForKey:(id)aKey;



@end


@implementation NSDictionary (CategoryName)

- (id)objectOrNilForKey:(id)aKey {
    id object = [self objectForKey:aKey];
    return [object isEqual:[NSNull null]] ? nil : object;
}

@end
Run Code Online (Sandbox Code Playgroud)

然后你可以使用

[response objectOrNilForKey:@"field"];

如果您愿意,可以修改此项以返回空白字符串.