Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/115.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从json文件导入数据_Ios_Objective C - Fatal编程技术网

Ios 从json文件导入数据

Ios 从json文件导入数据,ios,objective-c,Ios,Objective C,我创建了一些json数据,并将其保存在xcode中名为quizdata.json的文件中。然后,我选择了项目目标并单击了编辑器/addbuild-Phase/Add-Copy-File-Build-Phase,选择了产品目录并在提供的空间中删除了quizdata.json文件。我没有指明子路径,因为我读到它不需要,也不知道它:( 然后,我在这个主函数的底部添加了四行,以导入文件并将其序列化到一个对象中 Imported Questions: (null) Program ended with e

我创建了一些json数据,并将其保存在xcode中名为
quizdata.json
的文件中。然后,我选择了项目目标并单击了编辑器/addbuild-Phase/Add-Copy-File-Build-Phase,选择了产品目录并在提供的空间中删除了
quizdata.json
文件。我没有指明子路径,因为我读到它不需要,也不知道它:(

然后,我在这个主函数的底部添加了四行,以导入文件并将其序列化到一个对象中

Imported Questions: (null)
Program ended with exit code: 0
你能解释为什么它是空的吗

主要 int main(int argc,const char*argv[] {

来自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];

(注意:您可以在上查看您的文件(仅供参考))

@Lukasz'Severiaan'Grela我不确定我是否理解您的评论,但我从本博客导入数据教程复制的代码中,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”分隔在单独的一行,分配给临时文件,并确保其有效。(在这种情况下,要做的第一件事是验证所有输入,以便准确知道哪一步失败。)json格式不正确。您链接的编辑器帮助了我。
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];