Skip to content

Instantly share code, notes, and snippets.

@PavelGnatyuk
Created December 19, 2013 10:15
Show Gist options
  • Save PavelGnatyuk/8037082 to your computer and use it in GitHub Desktop.
Save PavelGnatyuk/8037082 to your computer and use it in GitHub Desktop.
Objective C: Serialize to JSON
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSDictionary *attributes = @{ @"first": @"first value",
@"second" : @3.14,
@"third" : @[ @"one", @"two", @4, @5, @YES, @NO] };
if ( [NSJSONSerialization isValidJSONObject:attributes] ) {
NSError *error = nil;
NSData *json = [NSJSONSerialization dataWithJSONObject:attributes options:NSJSONWritingPrettyPrinted error:&error];
if ( json && !error ) {
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(@"json: %@", jsonString);
// Same written to a file
[jsonString writeToFile:@"json_file.json" atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment