以JSON格式的string文件,如何将filecontent读入NSDictionary

我的应用程序包中只有一个文件“xyz.txt”,只有JSON格式的文本。 我想打开文本文件的文件path,并将内容读取到NSDictionary。 怎么做。 我已经准备好了我的JSONstring。 只需要启动到NSdictionary。 如果我直接在代码中初始化,那么在evey键和值之前,我会需要很多@。 我想避免这种情况。 这就是原因,我把JSON放在一个文件“xyz.txt”

我有两种方法 – 1.我读取表单文件,并使用[[NSDictionary alloc] initWithContentsOfFile:filePath]; 2.我把这个string分配给了NSDictionay。 我一直想避免使用@

我知道我们可以通过NSData ID结果= [NSJSONSerialization JSONObjectWithData:数据选项:NSJSONReadingMutableContainers错误:&错误];

但即使在这种情况下,我们将需要使用@初始化string到NSData的所有键和值。

任何解决scheme,可以从文本文件读取JSON和输出分配给NSDictionary

{ "ABC": [ { "id": "01", "score": "0.2" }, { "id": "02", "score": "0.2" } ], "XYZ": [ { "id": "01", "score": "0.9" }, { "id": "02", "score": "0.9" } ], "PQR": [ { "id": "01", "score": "0.9" }, { "id": "02", "score": "0.3" }, { "id": "03", "score": "0.2" } ] } 

使用NSDatadataWithContentsOfFile方法获取文件数据(文件path应该是包中文件的path;有一个方法可以从app主包中获取资源的path)。

然后使用NSJSONSerializationJSONObjectWithData方法从JSON数据创build一个NSDictionary

JSON存储在文件中的string – > NSDictionary

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyDict" ofType:@"text"]; NSData * myDictData = [NSData dataWithContentsOfFile:filePath]; NSError *error; NSDictionary * myDictionary = [NSJSONSerialization JSONObjectWithData:myDictData options:NSJSONReadingMutableContainers error:&error]; if (error != nil) { NSLog(@"Error parsing JSON:\n%@",error.userInfo); return; }