NSDictionary+MTLJSONKeyPath.m 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //
  2. // NSDictionary+MTLJSONKeyPath.m
  3. // Mantle
  4. //
  5. // Created by Robert Böhnke on 19/03/14.
  6. // Copyright (c) 2014 GitHub. All rights reserved.
  7. //
  8. #import "NSDictionary+MTLJSONKeyPath.h"
  9. #import "MTLJSONAdapter.h"
  10. @implementation NSDictionary (MTLJSONKeyPath)
  11. - (id)mtl_valueForJSONKeyPath:(NSString *)JSONKeyPath success:(BOOL *)success error:(NSError **)error {
  12. NSArray *components = [JSONKeyPath componentsSeparatedByString:@"."];
  13. id result = self;
  14. for (NSString *component in components) {
  15. // Check the result before resolving the key path component to not
  16. // affect the last value of the path.
  17. if (result == nil || result == NSNull.null) break;
  18. if (![result isKindOfClass:NSDictionary.class]) {
  19. if (error != NULL) {
  20. NSDictionary *userInfo = @{
  21. NSLocalizedDescriptionKey: NSLocalizedString(@"Invalid JSON dictionary", @""),
  22. NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"JSON key path %1$@ could not resolved because an incompatible JSON dictionary was supplied: \"%2$@\"", @""), JSONKeyPath, self]
  23. };
  24. *error = [NSError errorWithDomain:MTLJSONAdapterErrorDomain code:MTLJSONAdapterErrorInvalidJSONDictionary userInfo:userInfo];
  25. }
  26. if (success != NULL) *success = NO;
  27. return nil;
  28. }
  29. result = result[component];
  30. }
  31. if (success != NULL) *success = YES;
  32. return result;
  33. }
  34. @end