2012-04-10 66 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);