使用我在cimgf.com上找到的以下代码将核心数据输入JSON文件:
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的新手,之前没有处理强类型语言。
答案 0 :(得分:1)
if (value == nil)
应该是if ([value isEqual:[NSNull null]])
- 大多数JSON解析器代表null
的显式NSNull
值,因为无法在nil
中存储NSDictionary
{1}}也不在NSArray
。