我必须与复杂的 API 和复杂的 JSON 响应进行交互。我使用的是 AFNetworking
,JSON 响应会自动转换为 NSDictionary
。
我不确定 JSON 结构将始终如我所期望的那样,因此我开始编写大量防御代码。
if (response &&
[response isKindOfClass:[NSDictionary class]] &&
[[response valueForKey:@"result"] isKinfOfClass:[NSString class]]....
我想知道是否可以编写一些将空 JSON 响应作为"template"并检查响应是否与模板“匹配”的代码。有人已经处理过这种问题了吗?
最佳答案
为了从 JASON 响应中将值插入到核心数据中,我一直在使用这个可以用作函数的类别
@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
关于ios - 正确检查 NSDictionary 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24612574/