Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Created May 22, 2018 01:15
Show Gist options
  • Save alexpaul/f1b2fac51361b007882c43f426868596 to your computer and use it in GitHub Desktop.
Save alexpaul/f1b2fac51361b007882c43f426868596 to your computer and use it in GitHub Desktop.
Parsing JSON in Objective-C
#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, @"jane@jane.com");
XCTAssertEqualObjects(person.phone, @"917-123-4567");
}
} else {
XCTFail(@"data is nil");
}
XCTAssertNotNil(path);
} else {
XCTFail(@"file NOT FOUND");
}
}
@end
@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
#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