0

cimgf.comで見つけた次のコードを使用してJSONファイルをCoreDataに入力します。

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パーサーは、またはに格納できないため、明示的なnull値をで表します。NSNullnilNSDictionaryNSArray

于 2013-01-12T20:53:11.343 に答える