0

使用我在 cimgf.com 上找到的以下代码将 JSON 文件输入到 Core Data 中:

NSString *filePathGPS = [[NSBundle mainBundle] pathForResource:@"gps_6kb" ofType:@"json"];


if (filePathGPS) {
    NSString *contentOfFile = [NSString stringWithContentsOfFile:filePathGPS encoding:NSUTF8StringEncoding error:nil];
    NSDictionary *jsonDict = [contentOfFile objectFromJSONString];

    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *areaName = [NSEntityDescription
                                  insertNewObjectForEntityForName:@"Area"
                                  inManagedObjectContext:context];

    NSDictionary *attributes = [[areaName entity] attributesByName];

    for (NSString *attribute in attributes) {
        for (NSDictionary * tempDict in jsonDict) {
            NSLog(@"Attribute =  %@", attribute);

            id value = [tempDict objectForKey:attribute];

            NSLog(@"Value =  %@", value);

            if (value == nil) {
                continue;
            }


            [areaName setValue:value forKey:attribute];
        }
    }


    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
}

我收到以下错误:

2013-01-12 12:11:09.548 SuperGatherData[1194:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "area2"; desired type = NSString; given type = NSNull; value = <null>.'

我明白为什么会发生错误,因为文件中的某些值是 null 而不是字符串。这是 JSON 数据的示例:

   {
        "area1": "International",
        "area2": null,
        "area3": null,
        "area4": null,
        "area5": null,
        "latitude": "-25.2447",
        "longtitude": "133.9453",
    },
    {
        "area1": "Alaska",
        "area2": "Anchorage & South Central Alaska ",
        "area3": null,
        "area4": null,
        "area5": null,
        "latitude": "61.2134",
        "longtitude": "-149.8672",
    },
    {
        "area1": "Alabama",
        "area2": null,
        "area3": null,
        "area4": null,
        "area5": null,
        "latitude": "34.4112",
        "longtitude": "-85.5737",
    },

并意识到我需要对以下行中的属性类型转换做一些事情:

for (NSString *attribute in attributes) {

我只是不知道那个修复是什么。我是 Objective-C 的新手,之前没有处理过强类型语言。

4

1 回答 1

1

if (value == nil)应该if ([value isEqual:[NSNull null]])改为 - 大多数 JSON 解析器通过 表示显式nullNSNull,因为不能存储nil在 anNSDictionary或 an 中NSArray

于 2013-01-12T20:53:11.343 回答