【问题标题】:Not Null validation for JSON Response iPhone AppJSON 响应 iPhone 应用程序的非空验证
【发布时间】:2012-04-10 09:18:15
【问题描述】:
目前我正在使用以下方法来验证数据是否为空。
if ([[response objectForKey:@"field"] class] != [NSNull class])
NSString *temp = [response objectForKey:@"field"];
else
NSString *temp = @"";
当响应字典包含数百个属性(和相应的值)时,就会出现问题。我需要为字典的每个元素添加这种条件。
还有其他方法可以完成吗?
对 Web 服务进行任何更改的任何建议(除了不将空值插入数据库)?
任何想法,任何人??
【问题讨论】:
标签:
iphone
objective-c
json
web-services
【解决方案1】:
我所做的是在 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
那么你就可以使用
[response objectOrNilForKey:@"field"];
如果你愿意,你可以修改它以返回一个空白字符串。
【解决方案2】:
首先有一点:你的测试不是惯用的,你应该使用
if (![[response objectForKey:@"field"] isEqual: [NSNull null]])
如果您希望将字典中值为 [NSNull null] 的所有键重置为空字符串,最简单的修复方法是
for (id key in [response allKeysForObject: [NSNull null]])
{
[response setObject: @"" forKey: key];
}
以上假设response 是一个可变字典。
但是,我认为您确实需要审查您的设计。如果数据库中不允许使用 [NSNull null] 值,则根本不应该允许它们。
【解决方案3】:
我不太清楚你需要什么,但是:
如果您需要检查 key 的值是否不为 NULL,您可以这样做:
for(NSString* key in dict) {
if( ![dict valueForKey: key] ) {
[dict setValue: @"" forKey: key];
}
}
如果你有一些必需的键,你可以创建静态数组,然后这样做:
static NSArray* req_keys = [[NSArray alloc] initWithObjects: @"k1", @"k2", @"k3", @"k4", nil];
然后在您检查数据的方法中:
NSMutableSet* s = [NSMutableSet setWithArray: req_keys];
NSSet* s2 = [NSSet setWithArray: [d allKeys]];
[s minusSet: s2];
if( s.count ) {
NSString* err_str = @"Error. These fields are empty: ";
for(NSString* field in s) {
err_str = [err_str stringByAppendingFormat: @"%@ ", field];
}
NSLog(@"%@", err_str);
}
【解决方案4】:
static inline NSDictionary* DictionaryRemovingNulls(NSDictionary *aDictionary) {
NSMutableDictionary *returnValue = [[NSMutableDictionary alloc] initWithDictionary:aDictionary];
for (id key in [aDictionary allKeysForObject: [NSNull null]]) {
[returnValue setObject: @"" forKey: key];
}
return returnValue;
}
response = DictionaryRemovingNulls(response);