JSONKeyMapper.m 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. //
  2. // JSONKeyMapper.m
  3. //
  4. // @version 1.2
  5. // @author Marin Todorov (http://www.underplot.com) and contributors
  6. //
  7. // Copyright (c) 2012-2015 Marin Todorov, Underplot ltd.
  8. // This code is distributed under the terms and conditions of the MIT license.
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  11. // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  13. //
  14. #import "JSONKeyMapper.h"
  15. #import <libkern/OSAtomic.h>
  16. @interface JSONKeyMapper()
  17. @property (nonatomic, strong) NSMutableDictionary *toModelMap;
  18. @property (nonatomic, strong) NSMutableDictionary *toJSONMap;
  19. @property (nonatomic, assign) OSSpinLock lock;
  20. @end
  21. @implementation JSONKeyMapper
  22. -(instancetype)init
  23. {
  24. self = [super init];
  25. if (self) {
  26. //initialization
  27. self.toModelMap = [NSMutableDictionary dictionary];
  28. self.toJSONMap = [NSMutableDictionary dictionary];
  29. }
  30. return self;
  31. }
  32. -(instancetype)initWithJSONToModelBlock:(JSONModelKeyMapBlock)toModel
  33. modelToJSONBlock:(JSONModelKeyMapBlock)toJSON
  34. {
  35. self = [self init];
  36. if (self) {
  37. __weak JSONKeyMapper* weakSelf = self;
  38. _JSONToModelKeyBlock = [^NSString* (NSString* keyName) {
  39. __strong JSONKeyMapper* strongSelf = weakSelf;
  40. //try to return cached transformed key
  41. if (strongSelf.toModelMap[keyName]) {
  42. return strongSelf.toModelMap[keyName];
  43. }
  44. //try to convert the key, and store in the cache
  45. NSString* result = toModel(keyName);
  46. OSSpinLockLock(&strongSelf->_lock);
  47. strongSelf.toModelMap[keyName] = result;
  48. OSSpinLockUnlock(&strongSelf->_lock);
  49. return result;
  50. } copy];
  51. _modelToJSONKeyBlock = [^NSString* (NSString* keyName) {
  52. __strong JSONKeyMapper *strongSelf = weakSelf;
  53. //try to return cached transformed key
  54. if (strongSelf.toJSONMap[keyName]) {
  55. return strongSelf.toJSONMap[keyName];
  56. }
  57. //try to convert the key, and store in the cache
  58. NSString* result = toJSON(keyName);
  59. OSSpinLockLock(&strongSelf->_lock);
  60. strongSelf.toJSONMap[keyName] = result;
  61. OSSpinLockUnlock(&strongSelf->_lock);
  62. return result;
  63. } copy];
  64. }
  65. return self;
  66. }
  67. -(instancetype)initWithDictionary:(NSDictionary *)map
  68. {
  69. self = [super init];
  70. if (self) {
  71. NSDictionary *userToModelMap = [map copy];
  72. NSDictionary *userToJSONMap = [self swapKeysAndValuesInDictionary:map];
  73. _JSONToModelKeyBlock = ^NSString *(NSString *keyName) {
  74. NSString *result = [userToModelMap valueForKeyPath:keyName];
  75. return result ? result : keyName;
  76. };
  77. _modelToJSONKeyBlock = ^NSString *(NSString *keyName) {
  78. NSString *result = [userToJSONMap valueForKeyPath:keyName];
  79. return result ? result : keyName;
  80. };
  81. }
  82. return self;
  83. }
  84. - (NSDictionary *)swapKeysAndValuesInDictionary:(NSDictionary *)dictionary
  85. {
  86. NSMutableDictionary *swapped = [NSMutableDictionary new];
  87. [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
  88. NSAssert([value isKindOfClass:[NSString class]], @"Expect keys and values to be NSString");
  89. NSAssert([key isKindOfClass:[NSString class]], @"Expect keys and values to be NSString");
  90. swapped[value] = key;
  91. }];
  92. return swapped;
  93. }
  94. -(NSString*)convertValue:(NSString*)value isImportingToModel:(BOOL)importing
  95. {
  96. return !importing?_JSONToModelKeyBlock(value):_modelToJSONKeyBlock(value);
  97. }
  98. +(instancetype)mapperFromUnderscoreCaseToCamelCase
  99. {
  100. JSONModelKeyMapBlock toModel = ^ NSString* (NSString* keyName) {
  101. //bail early if no transformation required
  102. if ([keyName rangeOfString:@"_"].location==NSNotFound) return keyName;
  103. //derive camel case out of underscore case
  104. NSString* camelCase = [keyName capitalizedString];
  105. camelCase = [camelCase stringByReplacingOccurrencesOfString:@"_" withString:@""];
  106. camelCase = [camelCase stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[camelCase substringToIndex:1] lowercaseString] ];
  107. return camelCase;
  108. };
  109. JSONModelKeyMapBlock toJSON = ^ NSString* (NSString* keyName) {
  110. NSMutableString* result = [NSMutableString stringWithString:keyName];
  111. NSRange upperCharRange = [result rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]];
  112. //handle upper case chars
  113. while ( upperCharRange.location!=NSNotFound) {
  114. NSString* lowerChar = [[result substringWithRange:upperCharRange] lowercaseString];
  115. [result replaceCharactersInRange:upperCharRange
  116. withString:[NSString stringWithFormat:@"_%@", lowerChar]];
  117. upperCharRange = [result rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]];
  118. }
  119. //handle numbers
  120. NSRange digitsRange = [result rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
  121. while ( digitsRange.location!=NSNotFound) {
  122. NSRange digitsRangeEnd = [result rangeOfString:@"\\D" options:NSRegularExpressionSearch range:NSMakeRange(digitsRange.location, result.length-digitsRange.location)];
  123. if (digitsRangeEnd.location == NSNotFound) {
  124. //spands till the end of the key name
  125. digitsRangeEnd = NSMakeRange(result.length, 1);
  126. }
  127. NSRange replaceRange = NSMakeRange(digitsRange.location, digitsRangeEnd.location - digitsRange.location);
  128. NSString* digits = [result substringWithRange:replaceRange];
  129. [result replaceCharactersInRange:replaceRange withString:[NSString stringWithFormat:@"_%@", digits]];
  130. digitsRange = [result rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet] options:kNilOptions range:NSMakeRange(digitsRangeEnd.location+1, result.length-digitsRangeEnd.location-1)];
  131. }
  132. return result;
  133. };
  134. return [[self alloc] initWithJSONToModelBlock:toModel
  135. modelToJSONBlock:toJSON];
  136. }
  137. +(instancetype)mapperFromUpperCaseToLowerCase
  138. {
  139. JSONModelKeyMapBlock toModel = ^ NSString* (NSString* keyName) {
  140. NSString*lowercaseString = [keyName lowercaseString];
  141. return lowercaseString;
  142. };
  143. JSONModelKeyMapBlock toJSON = ^ NSString* (NSString* keyName) {
  144. NSString *uppercaseString = [keyName uppercaseString];
  145. return uppercaseString;
  146. };
  147. return [[self alloc] initWithJSONToModelBlock:toModel
  148. modelToJSONBlock:toJSON];
  149. }
  150. + (instancetype)mapper:(JSONKeyMapper *)baseKeyMapper withExceptions:(NSDictionary *)exceptions
  151. {
  152. NSArray *keys = exceptions.allKeys;
  153. NSArray *values = [exceptions objectsForKeys:keys notFoundMarker:[NSNull null]];
  154. NSDictionary *toModelMap = [NSDictionary dictionaryWithObjects:values forKeys:keys];
  155. NSDictionary *toJsonMap = [NSDictionary dictionaryWithObjects:keys forKeys:values];
  156. JSONModelKeyMapBlock toModel = ^NSString *(NSString *keyName) {
  157. if (!keyName)
  158. return nil;
  159. if (toModelMap[keyName])
  160. return toModelMap[keyName];
  161. return baseKeyMapper.JSONToModelKeyBlock(keyName);
  162. };
  163. JSONModelKeyMapBlock toJson = ^NSString *(NSString *keyName) {
  164. if (!keyName)
  165. return nil;
  166. if (toJsonMap[keyName])
  167. return toJsonMap[keyName];
  168. return baseKeyMapper.modelToJSONKeyBlock(keyName);
  169. };
  170. return [[self alloc] initWithJSONToModelBlock:toModel modelToJSONBlock:toJson];
  171. }
  172. @end