Created
May 22, 2018 01:15
-
-
Save alexpaul/f1b2fac51361b007882c43f426868596 to your computer and use it in GitHub Desktop.
Parsing JSON in Objective-C
This file contains hidden or 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 <XCTest/XCTest.h> | |
#import "Person.h" | |
@interface ParsingJSONTests : XCTestCase | |
@end | |
@implementation ParsingJSONTests | |
- (void)testReadingJSONFile { | |
// Getting the path in the current bundle | |
NSString *path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"json" inDirectory:nil]; | |
if (path) { | |
// create data from that path | |
NSData *jsonData = [NSData dataWithContentsOfFile:path]; | |
NSError *error; | |
if (jsonData) { | |
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:[] error:&error]; | |
if (error) { | |
XCTFail(@"JSONSerialization error: %@", error.localizedDescription); | |
} else { | |
// create our Person object | |
Person *person = [[Person alloc] initWithDict:dict]; | |
XCTAssertEqualObjects(person.name, @"Jane"); | |
XCTAssertEqualObjects(person.email, @"[email protected]"); | |
XCTAssertEqualObjects(person.phone, @"917-123-4567"); | |
} | |
} else { | |
XCTFail(@"data is nil"); | |
} | |
XCTAssertNotNil(path); | |
} else { | |
XCTFail(@"file NOT FOUND"); | |
} | |
} | |
@end |
This file contains hidden or 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
@interface Person: NSObject | |
@property (copy, nonatomic, readonly) NSString *name; | |
@property (copy, nonatomic, readonly) NSString *email; | |
@property (copy, nonatomic, readonly) NSString *phone; | |
- (instancetype)initWithDict:(NSDictionary *)dict; | |
@end |
This file contains hidden or 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> | |
#import "Person.h" | |
@implementation Person | |
- (instancetype)initWithDict:(NSDictionary *)dict { | |
self = [super init]; | |
if (self) { | |
if (dict[@"name"]) | |
_name = dict[@"name"]; | |
if (dict[@"email"]) | |
_email = dict[@"email"]; | |
if (dict[@"phone"]) | |
_phone = dict[@"phone"]; | |
} | |
return self; // return person; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment