Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash on invalid key path #230

Merged
merged 5 commits into from
Feb 10, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion Mantle/MTLJSONAdapter.m
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,24 @@ - (id)initWithJSONDictionary:(NSDictionary *)JSONDictionary modelClass:(Class)mo
NSString *JSONKeyPath = [self JSONKeyPathForPropertyKey:propertyKey];
if (JSONKeyPath == nil) continue;

id value = [JSONDictionary valueForKeyPath:JSONKeyPath];
id value = JSONDictionary;
NSArray *JSONKeyPathComponents = [JSONKeyPath componentsSeparatedByString:@"."];
for (NSString *itemJSONKeyPathComponent in JSONKeyPathComponents) {
if (![value isKindOfClass:NSDictionary.class]) {
if (error != NULL) {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: NSLocalizedString(@"Invalid JSON dictionary", @""),
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"%@ could not be created because an invalid JSON dictionary was provided for keypath: %@", @""), NSStringFromClass(modelClass), JSONKeyPath],
};
*error = [NSError errorWithDomain:MTLJSONAdapterErrorDomain code:MTLJSONAdapterErrorInvalidJSONDictionary userInfo:userInfo];
}
return nil;
}

value = [value valueForKey:itemJSONKeyPathComponent];
if (value == nil) break;
}

if (value == nil) continue;

@try {
Expand Down
16 changes: 16 additions & 0 deletions MantleTests/MTLJSONAdapterSpec.m
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,22 @@
expect([MTLJSONAdapter JSONDictionaryFromModel:model]).to.equal(values);
});

it(@"should return nil and error with an invalid key path from JSON",^{

NSDictionary *values = @{
@"username": @"foo",
@"nested": @"bar",
@"count": @"0"
};

NSError *error = nil;
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLTestModel.class fromJSONDictionary:values error:&error];
expect(model).beNil();
expect(error).notTo.beNil();
expect(error.domain).to.equal(MTLJSONAdapterErrorDomain);
expect(error.code).to.equal(MTLJSONAdapterErrorInvalidJSONDictionary);
});

it(@"should return nil and an error with a nil JSON dictionary", ^{
NSError *error = nil;
MTLJSONAdapter *adapter = [[MTLJSONAdapter alloc] initWithJSONDictionary:nil modelClass:MTLTestModel.class error:&error];
Expand Down