Created
November 7, 2013 18:33
-
-
Save krhoyt/7359568 to your computer and use it in GitHub Desktop.
Parse JSON content from a file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- ( 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