Permalink
Browse files

Merge pull request #230

  • Loading branch information...
2 parents bacacf5 + df03aa9 commit dcb2f9de603fc1ed2d71a36b77969beb62fc9381 @jspahrsummers jspahrsummers committed Feb 10, 2014
Showing with 35 additions and 1 deletion.
  1. +20 −1 Mantle/MTLJSONAdapter.m
  2. +15 −0 MantleTests/MTLJSONAdapterSpec.m
View
@@ -106,7 +106,26 @@ - (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 parsed because an invalid JSON dictionary was provided for key path \"%@\"", @""), 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 {
@@ -73,6 +73,21 @@
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];

0 comments on commit dcb2f9d

Please sign in to comment.