How do I parse JSON from a file in iOS? [closed] How do I parse JSON from a file in iOS? [closed] ios ios

How do I parse JSON from a file in iOS? [closed]


  1. Create empty text file (New File/Other/Empty) e.g. "example.json"

  2. Paste json string into the file.

  3. 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; }