How to deal with NSNull
7933 ワード
"somevalue": "<null>"
Sometimes when we receive the above JSON from server side, when we parse the JSON we will get NSNull. If we call a method on this object, the app will crash and generate the following error for example.
-[NSNull length]: unrecognized selector sent to instance 0x388a4a70
in order to prevent this, we have several solutions
- there is a property called
removesKeysWithNullValues
in AFNetworking. If we set it to YES, all the NSNull will become nil and we can use it without crash.
((AFJSONResponseSerializer *)manager.responseSerializer).removesKeysWithNullValues = YES;
- use the method
AFJSONObjectByRemovingKeysWithNullValues
originated from here
id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
if ([JSONObject isKindOfClass:[NSArray class]]) {
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
for (id value in (NSArray *)JSONObject) {
if (![value isEqual:[NSNull null]]) {
[mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
}
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
} else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
id value = (NSDictionary *)JSONObject[key];
if (!value || [value isEqual:[NSNull null]]) {
[mutableDictionary removeObjectForKey:key];
} else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
}
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
}
return JSONObject;
}
Author And Source
この問題について(How to deal with NSNull), 我々は、より多くの情報をここで見つけました https://qiita.com/tina79515/items/6a7f94d72bc024815592著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .