Created
January 13, 2015 06:28
-
-
Save zeayes/0bab6afa98eaf2ae98b6 to your computer and use it in GitHub Desktop.
objective c json encoding example
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 { | |
NSArray *people = @[ | |
@{@"name": @"John", @"age": @23, @"gender": @YES}, | |
@{@"name": @"Tom", @"age": @25, @"gender": @YES}, | |
@{@"name": @"Lucy", @"age": @20, @"gender": @NO}, | |
]; | |
if ([NSJSONSerialization isValidJSONObject:people]) { | |
NSError *error; | |
NSData *data = [NSJSONSerialization dataWithJSONObject:people options:NSJSONWritingPrettyPrinted error:&error]; | |
NSLog(@"json serialization data: %@", data); | |
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; | |
NSLog(@"json serialization string: %@", jsonString); | |
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; | |
NSLog(@"%@", [json class]); | |
if ([json isKindOfClass: [NSArray class]]) { | |
NSDictionary *Tom = [(NSArray *)json objectAtIndex:1]; | |
NSLog(@"%@", Tom); | |
BOOL gender = [[Tom objectForKey:@"gender"] boolValue]; | |
NSLog(@"Tom's gender: %@", gender ? @"YES": @"NO"); | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment