RestKit返回null值为&#34; <null>&#34;来自JSON响应</null>

时间:2013-01-04 02:32:39

标签: ios xcode json restkit nsuserdefaults

我从restkit获得的JSON响应中有一个奇怪的错误。

我向服务器发送了一个帖子请求,并以"someVal" = "<null>"代替"someVal" = null进行回复。这导致xcode以一种非常奇怪的方式处理它,我似乎无法将它保存到NSUserDefaults因为它...我不能删除它,就像我会正常的空值...它会被检测为什么?我想也许是一根绳子?但是没有......由于某种原因,它不能将其保存为字符串。

1 个答案:

答案 0 :(得分:1)

我不认为这个问题仅限于RestKit。更多来自为您提供JSON的服务器。我在使用AFNetworking时遇到了同样的问题。

我发现这个词典类别可用于修剪空值并用空字符串替换。您可以使用它,或者只是将逻辑删除以对空值进行排序。

@implementation NSDictionary (JRAdditions)

- (NSDictionary *) dictionaryByReplacingNullsWithStrings {

    NSMutableDictionary *replaced = [NSMutableDictionary dictionaryWithDictionary:self];
    const id nul = [NSNull null];
    const NSString *blank = @"";

    for(NSString *key in self) {
        const id object = [self objectForKey:key];
        if(object == nul) {
            //pointer comparison is way faster than -isKindOfClass:
            //since [NSNull null] is a singleton, they'll all point to the same
            //location in memory.
            [replaced setObject:blank forKey:key];
        }
    }
    return [NSDictionary dictionaryWithDictionary:replaced];
}

+ (NSDictionary *)dictionaryByReplacingNullsWithStrings:(NSDictionary *)dict {
    NSMutableDictionary *replaced = [NSMutableDictionary dictionaryWithDictionary:dict];
    const id nul = [NSNull null];
    const NSString *blank = @"";

    for(NSString *key in dict) {
        const id object = [dict objectForKey:key];
        if(object == nul) {
            //pointer comparison is way faster than -isKindOfClass:
            //since [NSNull null] is a singleton, they'll all point to the same
            //location in memory.
            [replaced setObject:blank forKey:key];
        }
    }
    return [NSDictionary dictionaryWithDictionary:replaced];
}

@end

// you can use this category on your dictionaries.
NSDictionary *jsonDict = JSON;
jsondict = [jsonDict dictionaryByReplacingNullsWithStrings];