ios - 正确检查 NSDictionary 结构

标签 ios objective-c json coding-style nsdictionary

我必须与复杂的 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/

相关文章:

javascript - JSON 中位置 0 的意外标记 u(但仅在某些时候)

ios - UICollectionViewFlowLayout 中有多个补充 View ?

ios - Xcode 9 的安全区域

ios - 在代码中使用 tintColor 绘制像 UITabBar 这样的渐变

ios - 将数组传递给 NSObject 类

objective-c - 苹果LLVM编译器3.1错误?

javascript - Java - Rest 端点返回图像(如果可用)和 JSON(如果不可用)

javascript - ASP.NET MVC - 返回 JavascriptResult 和 Json 参数

ios - UICollectionViewCell AutoLayout 基于 UILabel 动态高度

iphone - 如果条件不工作则赋值