How do I parse JSON from a file in iOS? [closed]
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];
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 } }
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; }