12

I'm developing an iPhone app and I need to show stored data in a TableView. After some research I decided that JSON would be best fit for storing the data. However, I couldn't find any tutorials explaining how to read JSON as a local file rather than from a remote source, as often is the case.

Any tutorials you could recommend?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
es1
  • 1,231
  • 3
  • 14
  • 27
  • When you say _local file_, are you saying the JSON file is stored in the Documents directory or embedded as a resource in the app bundle? – neilco Oct 15 '13 at 17:25
  • By the way, while JSON is a fine format (esp for exchanging data with a server), if this is a local resource only, a [property list](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html#//apple_ref/doc/uid/10000048-CJBGDEGD) (aka a "plist" file) might be simpler. You create a property list file with `[dictionary writeToFile:path atomically:YES];`. You read a plist with `NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:path];`. This is less cumbersome than using JSON. – Rob Oct 15 '13 at 19:09

2 Answers2

23

First of all: you need to load your local json string. Assuming the jsonstring is inside your project, to load it, first create nsstring pointing to the file:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"THENAMEOFTHEFILE" ofType:@"EXTENSIONOFYOUTFILE"];

second, load the data of file:

NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];

third, parse the data:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:content options:kNilOptions error:nil];
Nagarjun
  • 6,557
  • 5
  • 33
  • 51
Luciano Rodríguez
  • 2,239
  • 3
  • 19
  • 32
15

You can use NSJSONSerialization for this.

NSError *deserializingError;
NSURL *localFileURL = [NSURL fileURLWithPath:pathStringToLocalFile];
NSData *contentOfLocalFile = [NSData dataWithContentsOfURL:localFileURL];
id object = [NSJSONSerialization JSONObjectWithData:contentOfLocalFile 
                                            options:opts 
                                              error:&deserializingError];
matehat
  • 5,214
  • 2
  • 29
  • 40
  • `NSURL` does not have a method named `urlWithString`. If you wish to create an `NSURL` from a file path, you need to use `NSURL fileURLWithPath:`. – rmaddy Oct 15 '13 at 18:18
  • Sorry, capitalization was wrong, it should have been `URLWithString`. But you're right `fileURLWithPath:` is the way to go for file paths – matehat Oct 15 '13 at 18:24
  • 4
    I used: `NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"employees" ofType:@"json"]; NSData *data = [NSData dataWithContentsOfFile:jsonPath]; NSError *error = nil; id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];` – es1 Oct 15 '13 at 19:08