0

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

我向服务器发出一个 post 请求,它响应"someVal" = "<null>"而不是"someVal" = null. 这导致 xcode 以一种非常奇怪的方式处理它,因此我似乎无法将其保存到 NSUserDefaults ......而且我不能像正常的空值一样删除它......它会被检测为什么?我想也许是一个字符串?但是不……由于某种原因,它不能将其保存为字符串。

4

1 回答 1

1

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

我找到了这个 Dictionary 类别,您可以使用它来删除空值并替换为空字符串。您可以使用它或只是将逻辑撕掉以对您的空值进行排序。

@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];
于 2013-01-04T15:44:44.440 回答