ios - arrayWithContentsOfFile 和 arrayWithContentsOfURL 无

标签 ios objective-c json plist

当我调用 [NSArray arrayWithContentsOfFile:] 时,我得到了 nil。

NSURL *fileURL = [NSURL URLWithString:className relativeToURL:[self JSONDataRecordsDirectory]];
return [NSArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@", [fileURL path]]];

或者,我在调用时也得到 nil:

[NSArray arrayWithContentsOfURL:]

我所有文件的结果都在 JSON 中: https://gist.github.com/neverbendeasy/03d047a6789b0ae14e1f

当我检查 fileURLs 时,数据就在那里。

我错过了什么?

最佳答案

您不能使用 NSArray arrayWith... 加载 JSON 文件。该方法只能加载以数组为根的plist文件。

如果您的文件是 JSON 文件,您应该使用:

NSData *jsonData = [NSData dataWithContentsOfURL:fileURL];
NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (jsonArray) {
    // do something with jsonArray
} else {
    NSLog(@"Couldn't load JSON from %@: %@", fileURL, error);
}

这假设 JSON 文件的顶层是一个数组。

关于ios - arrayWithContentsOfFile 和 arrayWithContentsOfURL 无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556166/

相关文章:

UIView 中的 iOS UIScrollView

json - nodejs res.json在html中显示

ios - 如何在 Alamofire 中使用 NetworkReachabilityManager

ios - 如何根据背景图像颜色更改 UILabel 文本颜色?

ios - 无法同时满足 Storyboard中嵌入的 AVPlayerViewController 的约束警告

ios - 使 UIScrollView 中的顶部图像在 ScrollView 边界上放大?

ios - 快速将JSON值解析为全局数组

json - 如何通过 angularjs $resource 访问 json 中的嵌套对象

ios - 使用 iOS 编码 mpeg-1 视频

ios - 带有变换的 CGPathCreateWithEllipseInRect