问题
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"
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
I know we can do via NSData id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
but even in that case we will need to initialize string to NSData with @ for all key and value.
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"
}
]
}
回答1:
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).
Then use NSJSONSerialization's JSONObjectWithData method to create a NSDictionary from the JSON data.
回答2:
JSON in string stored in file -> 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;
}
来源:https://stackoverflow.com/questions/30557001/file-with-string-in-json-format-how-to-read-filecontent-into-nsdictionary