从json文件导入数据

时间:2014-04-17 12:57:26

标签: ios objective-c

我创建了一些json数据并将其保存在xcode中名为quizdata.json的文件中。然后,我选择了项目目标,然后单击编辑器/添加构建阶段/添加复制文件构建阶段,选择产品目录并将quizdata.json文件放在提供的空间中。我没有指出一个子路径,因为我认为它不是必需的,我不知道:(

然后我在这个main函数的底部添加了四行来导入文件并将其序列化为一个对象。但是,当我运行代码时,它应该在输出json数据时显示null

Imported Questions: (null)
Program ended with exit code: 0

你能解释为什么它是空的吗?

主     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:@"quizdata" ofType:@"json"];
        NSArray* Questions = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
                                                         options:kNilOptions
                                                           error:&err];
        NSLog(@"Imported Questions: %@", Questions);
    }
    return 0;
}

来自quizdata.json的样本

[{ "question" : "Do you like hairy fruit ?????????????????????????????", "answer1": "yes", "answer2": "no because my mouhth is like a large elastic band on tuesdays", "answer3": "maybe wonder never tried it but i should naturally", "answer4":"of course i do you beast of a man with a hairy nose", "correctAnswer": "yes", "unique": "1", "name": "fruitquiz", "quizId: 1"}
{ "question" : "Do you like fruit", "answer1": "yes", "answer2": "no", "answer3": "maybe", "answer4":"of course", "correctAnswer": "yes", "unique": "2", "name": "fruitquiz", "quizId: 1"}
...

1 个答案:

答案 0 :(得分:1)

1)确保Sure文件在资源中可用。

2)检查 NSData 长度。 (如果数据长度为零则可能是您的json文件问题,请确保您正在验证json文件)

3)根据需要在 NSArray NSDictionary 中保存数据。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

(注意:您可以在http://www.jsoneditoronline.org/上查看您的文件(仅供参考))