我必须与复杂的API和复杂的JSON响应进行交互。我使用AFNetworking
并将JSON响应自动转换为NSDictionary
。
我不确定JSON结构总是会像我期待的那样,所以我开始编写很多防御性代码。
if (response &&
[response isKindOfClass:[NSDictionary class]] &&
[[response valueForKey:@"result"] isKinfOfClass:[NSString class]]....
我想知道是否有用可以将一些空JSON响应的代码写成"模板"并检查响应是否会匹配"用模板。有人已经处理过这类问题吗?
答案 0 :(得分:1)
用于从JASON响应中将值插入Core Data我一直在使用此类别可以用作函数
@implementation NSManagedObject (safeSetValuesKeysWithDictionary)
- (void)safeSetValuesForKeysWithDictionary:(NSDictionary *)keyedValues
{
NSDictionary *attributes = [[self entity] attributesByName];
for (NSString *attribute in attributes) {
id value = [keyedValues objectForKey:attribute];
if (value == nil) {
// Don't attempt to set nil, or you'll overwite values in self that aren't present in keyedValues
continue;
}
NSAttributeType attributeType = [[attributes objectForKey:attribute] attributeType];
if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSNumber class]])) {
value = [value stringValue];
} else if (((attributeType == NSInteger16AttributeType) || (attributeType == NSInteger32AttributeType) || (attributeType == NSInteger64AttributeType) || (attributeType == NSBooleanAttributeType)) && ([value isKindOfClass:[NSString class]])) {
value = [NSNumber numberWithInteger:[value integerValue]];
} else if ((attributeType == NSFloatAttributeType) && ([value isKindOfClass:[NSString class]])) {
value = [NSNumber numberWithDouble:[value doubleValue]];
} else if ((attributeType == NSDateAttributeType) && ([value isKindOfClass:[NSString class]])) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
value = [dateFormat dateFromString:[[value componentsSeparatedByString: @"."] objectAtIndex:0]];
} else if ((attributeType == NSDoubleAttributeType) && ([value isKindOfClass:[NSString class]])) {
value = [NSNumber numberWithDouble:[value doubleValue]];
}
[self setValue:value forKey:attribute];
}
}
@end