我有用户信息字典,它是从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>";
}
发布于 2016-06-03 00:37:31
一个更先进的解决方案:
@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
发布于 2014-07-16 08:45:06
最简单的方法是循环遍历字典的可变副本,如果值是
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,否则您需要发布副本字典)
发布于 2014-07-16 08:32:44
首先,"<null>"
不是有效的JSON值。
这样写它,它只是一个包含单词<null>
的字符串。
在JSON中,null是以这种方式编写的。
{ "value": null }
因此,如果无法更新web服务以返回有效的json,我建议您在第一个实例中对JSON字符串执行替换操作。然后,当您拥有有效的JSON值时,只需使用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
实例。
https://stackoverflow.com/questions/24775544
复制相似问题