Reputation: 159
How can I parse my JSON file stored in the application?
These are in my JSON file contents:
[{"number":"01001","lieu":"paris"}{"number":"01002","lieu":"Dresden"}]
I’ve tried the following code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"json"];
//création d'un string avec le contenu du JSON
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
//Parsage du JSON à l'aide du framework importé
NSDictionary *json = [myJSON JSONValue];
NSArray *statuses = [json objectForKey:@"number"];
for (NSDictionary *status in statuses)
{
NSLog(@"%@ ", [status objectForKey:@"lieu"]);
}
Upvotes: 3
Views: 22807
Reputation: 7439
Here is a suggested full implementation:
NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"json"];
if (!jsonFilePath) {
// ... do something ...
}
NSError *error = nil;
NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:jsonFilePath];
[inputStream open];
id jsonObject = [NSJSONSerialization JSONObjectWithStream: inputStream
options:kNilOptions
error:&error];
[inputStream close];
if (error) {
// ... do something ...
}
Upvotes: 2
Reputation:
Firstly, note there’s a comma missing between the two objects in your JSON string.
Secondly, note that your JSON string contains a top-level array. So, instead of:
NSDictionary *json = [myJSON JSONValue];
use:
NSArray *statuses = [myJSON JSONValue];
Each element in the array is an object (a dictionary) with two name-value pairs (key-object pairs), one for number
and another one for lieu
:
for (NSDictionary *status in statuses) {
NSString *number = [status objectForKey:@"number"];
NSString *lieu = [status objectForKey:@"lieu"];
…
}
You might also want to check whether the file could be read:
//Creating a string with the contents of JSON
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
if (!myJSON) {
NSLog(@"File couldn't be read!");
return;
}
Upvotes: 25