Skip to content

Instantly share code, notes, and snippets.

@krhoyt
Created November 7, 2013 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krhoyt/7359568 to your computer and use it in GitHub Desktop.
Save krhoyt/7359568 to your computer and use it in GitHub Desktop.
Parse JSON content from a file.
- ( NSArray * ) parseJSONContent : ( NSString * ) fileName
{
NSArray * colors;
NSArray * directories;
NSData * buffer;
NSError * error;
NSFileHandle * handle;
NSFileManager * manager;
NSMutableString * path;
NSString * blue;
NSString * contents;
NSString * green;
NSString * red;
manager = [NSFileManager defaultManager];
directories = NSSearchPathForDirectoriesInDomains( NSDesktopDirectory, NSUserDomainMask, YES );
path = [[NSMutableString alloc] initWithString : [directories objectAtIndex : 0]];
[path appendString: @"/"];
[path appendString: fileName];
// NSLog( @"%@", path );
if( [manager fileExistsAtPath : path] == NO )
{
NSLog( @"File not found." );
} else {
// NSLog( @"File exists." );
// Handle
handle = [NSFileHandle fileHandleForReadingAtPath : path];
// Read NSData
buffer = [handle readDataToEndOfFile];
// To string
contents = [[NSString alloc] initWithData : buffer encoding : NSUTF8StringEncoding];
// Log contents
NSLog( @"%@", contents );
// Close file
[handle closeFile];
// Parse JSON content
// Returns NSArray
colors = [NSJSONSerialization JSONObjectWithData : buffer options : NSJSONReadingMutableContainers error : &error];
if( !colors )
{
NSLog( @"Error parsing JSON: %@", error );
} else {
// Iterate over JSON values
for( NSDictionary * item in colors )
{
red = [item valueForKey : @"red"];
green = [item valueForKey : @"green"];
blue = [item valueForKey : @"blue"];
NSLog( @"Red: %@, Green: %@, Blue: %@", red, green, blue );
}
}
}
return colors;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment