试图在Objective-C中读取JSON文件

时间:2013-07-17 17:48:30

标签: objective-c json

我正在尝试在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对象出现为null?谁能看到我做错了什么?仅仅为了记录,我已经尝试在我的JSON文件中检查无关的空间,并尝试将JSON文件放在我的应用程序文件夹中的不同位置,但没有任何工作。

感谢所有回复的人。

1 个答案:

答案 0 :(得分:2)

从您的源代码和您的评论中我假设应用程序是作为一个构建的 “命令行工具”。在这种情况下,“Target MemberShip”复选框实际上是 已禁用自定义资源文件,如JSON文件。

作为解决方法:

  • 转到目标的“构建阶段”。
  • 点击“添加构建阶段”,然后选择“添加复制文件”。
  • 在新构建阶段,单击+并选择您的JSON文件。

对于命令行工具,您选择哪个“目标”似乎并不重要。 我用“目的地:资源”测试了它。 JSON文件复制在同一个文件中 包含可执行文件的目录。现在

[[NSBundle mainBundle] pathForResource:@"Transactions" ofType:@"json"];

应返回该路径,您可以从应用程序中读取该文件。