How do I parse JSON from a file in iOS? [closed]
Solution 1:
Create empty text file (New File/Other/Empty) e.g. "example.json"
Paste json string into the file.
-
Use these lines to get the data:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"]; NSData *data = [NSData dataWithContentsOfFile:filePath]; NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
Solution 2:
Swift 2.0 version of the accepted answer:
if let filePath = NSBundle.mainBundle().pathForResource("example", ofType: "json"), data = NSData(contentsOfFile: filePath) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
}
catch {
//Handle error
}
}
Solution 3:
I have followed this and it is working fine
NSError *error = nil;
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"messages"
ofType:@"json"];
NSData *dataFromFile = [NSData dataWithContentsOfFile:filePath];
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:dataFromFile
options:kNilOptions
error:&error];
if (error != nil) {
NSLog(@"Error: was not able to load messages.");
return nil;
}