我试图在我的 Objective-C 应用程序中读取一个 json 文件,但不幸的是我得到了一个 RuntimeException。确切的错误是:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
我的 json 文件名为“Transactions.json
[{ "transaction": "300001", "date": "1/1/11", "type": "ABC", "status": "State1" },
{ "transaction": "300002", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300003", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300004", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300005", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300006", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300007", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300008", "date": "2/2/12", "type": "XYZ", "status": "State2" },
{ "transaction": "300009", "date": "3/3/13", "type": "ABC", "status": "State3" },
{ "transaction": "300010", "date": "4/4/14", "type": "XYZ", "status": "State4" } ]
我在文件中读取的方法如下所示:
int main(int argc, const char * argv[])
{
@autoreleasepool {
// Create the managed object context
NSManagedObjectContext *context = managedObjectContext();
// Custom code here...
// Save the managed object context
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
exit(1);
}
NSError *err = nil;
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"Transactions" ofType:@"json"];
NSLog(@"Hello: %@", dataPath);
NSArray *transaction = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath] options:kNilOptions error:&err];
NSLog(@"Transaction list: %@", transaction);
}
return 0;
}
我不明白的是,当我读取 JSON 文件时,为什么 NSData 对象显示为空?谁能看到我做错了什么?只是为了记录,我尝试检查我的 JSON 文件中的无关空格,并尝试将 JSON 文件放在我的应用程序文件夹中的不同位置,但没有任何效果。
提前感谢所有回复的人。