Created
December 19, 2013 10:15
-
-
Save PavelGnatyuk/8037082 to your computer and use it in GitHub Desktop.
Objective C: Serialize to JSON
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
#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