【发布时间】:2019-04-14 14:36:16
【问题描述】:
我创建了一些 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"}
...
【问题讨论】:
-
@Lukasz'Severiaan'Grela 我不确定我是否理解您的评论,但是在我从本博客教程复制的用于导入数据raywenderlich.com/12170/…的代码中,err 设置为 nil >
-
是的,您最初将其设置为 nil 并调用 NSJSOMSerialization JSONObjectWithData... 如果出现错误,会将其设置为 NSError,因此请将其放在 NSLog 之前:
if(err) NSLog("Error %@",[err description]); -
@Lukasz'Severiaan'Grela 好的,谢谢。 json 数据有问题....“数据已损坏,无法读取。” (字符 375 周围的对象中的键没有值。) UserInfo=0x100515060 {NSDebugDescription=字符 375 周围的对象中的键没有值。}
-
问题解决了吗?
-
1) 检查“dataPath”是否有效。 2)将“dataWithContentsOfFile”拆分为单独的行,分配给一个临时文件,并确保它是有效的。 (在这种情况下要做的第一件事是验证您的所有输入,以便您准确知道哪个步骤失败了。)
标签: ios objective-c