2012-04-10 67 views
4

当前我正在使用以下方法验证数据是否为空。对JSON响应无效验证iPhone应用程序

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

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

任何其他方式来完成?

任何对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 

然后,你可以使用

[response objectOrNilForKey:@"field"];

您可以修改这个,如果你想返回一个空字符串喜欢。

+0

好戏。完美解决方案谢谢。大量使用类别。 – Prazi 2012-11-28 05:51:47

0

首先一个小点:你的测试是不地道,你应该使用

if (![[response objectForKey:@"field"] isEqual: [NSNull null]]) 

如果你想在你的字典中有[NSNull null]值被重置为空字符串的所有按键,最简单的方法修复它是

for (id key in [response allKeysForObject: [NSNull null]]) 
{ 
    [response setObject: @"" forKey: key]; 
} 

以上假定response是一个可变的字典。

但是,我认为你真的需要检查你的设计。如果数据库中不允许使用[NSNull null]值,则不应该允许这些值。

0

这对我来说不是很清楚你需要什么,但:

如果您需要检查项的值是否不为空,你可以这样做:

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); 
} 
0
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);