首页 文章

dictionaryWithContentsOfFile返回Nil而不是NSdictionary

提问于
浏览
1

我创建了一个名为Dict.json的文件 . 该文件的内容是有效的json包含的

{“mydata”:[{“A”:4,“B”:14,“C”:7},{“A”:4,“B”:12,“C”:7},{“A “:34,”B“:154,”C“:6},{”A“:34,”B“:162,”C“:6}]}

我想从这个文件创建一个NSDictonary . 我尝试了以下但它返回nil .

NSString * filePath = [[NSBundle mainBundle] pathForResource:@“Dict”ofType:@“json”]; NSMutableDictionary * newArr1 = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];

我也在检查文件不是零;

NSData *myData = [NSData dataWithContentsOfFile:filePath];
if (myData) {
    NSLog("There is Data in File !!!!")  
}

2 回答

  • 2

    来自文档

    (id)dictionaryWithContentsOfFile:(NSString *)path参数path完整路径名或相对路径名 . 由path标识的文件必须包含属性列表的字符串表示形式,其根对象是字典 . 返回值包含路径中字典的新字典,如果存在文件错误或文件内容是字典的无效表示,则为nil .

    如上所述,您只能使用plist文件而不是.json创建字典 + (id)dictionaryWithContentsOfFile:(NSString *)path .

  • 0

    要加载 json 数据,您需要 NSJSONSerialization 从文件中获取 json 数据

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Dict" ofType:@"json"]; 
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
    NSMutableDictionary *dic1 = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil] mutableCopy];
    

    您的代码仅适用于 plist 文件,而不适用于 json 文件 .

相关问题