gpt4 book ai didi

ios - 从 json 文件导入数据

转载 作者:行者123 更新时间:2023-11-29 03:02:45 24 4
gpt4 key购买 nike

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

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

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) 确保文件在资源中可用。

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

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

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/上查看您的文件(仅供引用))

关于ios - 从 json 文件导入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23133777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com