带有JSON格式字符串的文件,如何将文件内容读入NSDictionary [英] File with string in JSON format , how to read filecontent into NSDictionary
问题描述
我的应用程序捆绑包中有一个文件"xyz.txt",其中只有JSON格式的文本. 我想打开文本文件的文件路径,然后将内容读取到NSDictionary.怎么做. 我已经准备好了JSON字符串.只需初始化NSdictionary.如果我直接在代码中初始化,则在传递键和值之前,我需要很多@.我想避免这种情况.这就是原因,我将JSON放在文件"xyz.txt"中
I have a file-"xyz.txt" in my applicaion bundle with just JSON formatted text. I want to open the filepath of the text file and read the content to NSDictionary. How to do that. I already have my JSON string ready. Just need to initliaze to NSdictionary. If I directly initilize in code , i would need lot of @ before evey key and value. and I want to avoid that. That is the reason , i put JSON in a file-"xyz.txt"
我有两种方法- 1.我读取表单文件并使用[[NSDictionary alloc] initWithContentsOfFile:filePath]进行分配; 2.我用很多@将字符串分配给NSDictionay. 我想避免一直使用@
I have two ways - 1.I read form file and assign it using [[NSDictionary alloc] initWithContentsOfFile:filePath]; 2.I assign the string to NSDictionay with lot of @. I want to avoid using @ all the time
我知道我们可以通过NSData做 id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers错误:&错误];
I know we can do via NSData id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
但是即使在这种情况下,我们也需要使用@来将所有键和值的字符串初始化为NSData.
but even in that case we will need to initialize string to NSData with @ for all key and value.
任何可以从文本文件读取json并将输出分配给NSDictionary的解决方案
Any solution that can read the json from a text file and output assign to a 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"
}
]
}
推荐答案
使用NSData
的dataWithContentsOfFile
方法获取文件数据(文件路径应为捆绑软件中文件的路径;有一种方法可以从应用程序主捆绑包中获取资源的路径).
Get the file's data using NSData
's dataWithContentsOfFile
method (the file path should be the path to the file in the bundle; there is a method that can get you the path of a resource from the app main bundle).
然后使用NSJSONSerialization
的JSONObjectWithData
方法从JSON数据创建NSDictionary
.
Then use NSJSONSerialization
's JSONObjectWithData
method to create a NSDictionary
from the JSON data.
这篇关于带有JSON格式字符串的文件,如何将文件内容读入NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!