繁体   English   中英

如何删除包含“ <null> ”(来自NSDictionary)

[英]How to remove a string containing “<null>” from an NSDictionary

我有用户信息字典,该信息从Web服务中获取。 有些字段的内容是私有的,因此包含NULL。 我如何将值转换为空字符串,无论哪里存在null值,如以下字典中所示:

{
"about_me" = "<null>";
"contact_number" = 123456798798;
"display_name" = "err";
followers = 0;
following = 4;
gender = "-";
posts = 0;
"user_id" = 18;
username = charge;
website = "<null>";
}

最简单的方法是遍历字典的可变副本,如果值是
null将值设置为所需的值。

NSMutableDictionary *mutableDict = [dict mutableCopy];
for (NSString *key in [dict allKeys]) {
    if ([dict[key] isEqual:[NSNull null]]) {
        mutableDict[key] = @"";//or [NSNull null] or whatever value you want to change it to
    }
}
dict = [mutableDict copy];

如果字典中的值实际上是"<null>" ,则用[dict[key] isEqualToString:@"<null>"]替换条件

(假设您使用的是ARC,否则您需要释放副本的字典)

首先, "<null>"不是有效的JSON空值。
这样写,它只是一个包含单词<null>的字符串

在JSON中,以这种方式写入null。

{ "value": null }

因此,如果您无法更新Web服务以返回有效的json,建议您在第一个实例中对JSON字符串进行替换。 然后,当您具有有效的JSON空值时,只需使用NSJSONSerialization处理NSJSONSerialization

NSString *json = @"{ \"value\": null }";
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];

NSLog(@"%@", jsonObject);

此打印

2014-07-16 10:31:36.737 MacUtilities[30760:303] {
    value = "<null>";
}

并调试类的value

po [[jsonObject objectForKey:@"value"] class];
NSNull

这是因为NSJSONSerialization正确处理了null,将其转换为NSNull实例

更高级的解决方案:

@interface NSObject (NULLValidation)
- (BOOL)isNull ;
@end

@implementation NSObject (NULLValidation)

- (BOOL)isNull{
    if (!self) return YES;
    else if (self == [NSNull null]) return YES;
    else if ([self isKindOfClass:[NSString class]]) {
        return ([((NSString *)self)isEqualToString : @""]
                || [((NSString *)self)isEqualToString : @"null"]
                || [((NSString *)self)isEqualToString : @"<null>"]
                || [((NSString *)self)isEqualToString : @"(null)"]
                );
    }
    return NO;

}
@end


@interface NSDictionary (NullReplacement)
- (NSDictionary *) dictionaryByReplacingNullsWithString:(NSString*)string;
@end

@implementation NSDictionary (NullReplacement)

- (NSDictionary *) dictionaryByReplacingNullsWithString:(NSString*)string {
     NSMutableDictionary *replaced = [NSMutableDictionary dictionaryWithDictionary: self];

     NSString *blank = string;

    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj isNull]) {
            [replaced setObject:blank forKey: key];
        }
        else if ([obj isKindOfClass: [NSDictionary class]]) {
            [replaced setObject: [(NSDictionary *) obj dictionaryByReplacingNullsWithString:string] forKey: key];
        }
    }];

    return replaced ;
}
@end

Swift 3.0/4.0解决方案

JSON具有sub-dictionaries时,以下是解决方案。 这将大大-通过所有的dictionaries ,分-dictionariesJSON和删除NULL(NSNull) key-value从对JSON

extension Dictionary {

    func removeNull() -> Dictionary {
        let mainDict = NSMutableDictionary.init(dictionary: self)
        for _dict in mainDict {
            if _dict.value is NSNull {
                mainDict.removeObject(forKey: _dict.key)
            }
            if _dict.value is NSDictionary {
                let test1 = (_dict.value as! NSDictionary).filter({ $0.value is NSNull }).map({ $0 })
                let mutableDict = NSMutableDictionary.init(dictionary: _dict.value as! NSDictionary)
                for test in test1 {
                    mutableDict.removeObject(forKey: test.key)
                }
                mainDict.removeObject(forKey: _dict.key)
                mainDict.setValue(mutableDict, forKey: _dict.key as? String ?? "")
            }
            if _dict.value is NSArray {
                let mutableArray = NSMutableArray.init(object: _dict.value)
                for (index,element) in mutableArray.enumerated() where element is NSDictionary {
                    let test1 = (element as! NSDictionary).filter({ $0.value is NSNull }).map({ $0 })
                    let mutableDict = NSMutableDictionary.init(dictionary: element as! NSDictionary)
                    for test in test1 {
                        mutableDict.removeObject(forKey: test.key)
                    }
                    mutableArray.replaceObject(at: index, with: mutableDict)
                }
                mainDict.removeObject(forKey: _dict.key)
                mainDict.setValue(mutableArray, forKey: _dict.key as? String ?? "")
            }
        }
        return mainDict as! Dictionary<Key, Value>
    }
 }

您有一个不是数组的Dictionary。 也许您有一系列的字典。 枚举数组,并对每个字典的键值对进行null检查。

您可能已从JSON响应中解析了NSDictionary JSON可能包含null值,并且您使用的JSON解析器将null转换为[NSNull null] ,并且如果您尝试将字符串与该NSNull进行比较,则它NSNull 在这种情况下,请尝试以下操作:

if ([yourDictionary objectForKey:@"website"]== [NSNull null]) {
    // handle here
}

在swift-4中,而不是remove中,可以使用以下方法将空值替换为空字符串

func removeNullFromDict (dict : NSMutableDictionary) -> NSMutableDictionary
{
    let dic = dict;

    for (key, value) in dict {

        let val : NSObject = value as! NSObject;
        if(val.isEqual(NSNull()))
        {
            dic.setValue("", forKey: (key as? String)!)
        }
        else
        {
            dic.setValue(value, forKey: key as! String)
        }

    }

    return dic;
}

并且在以以下方式将dict赋予任何方法调用函数之前

let newdict = self.removeNullFromDict(dict: dict);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM