JSONKeyMapper.m 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. //
  2. // JSONKeyMapper.m
  3. //
  4. // @version 1.0.0
  5. // @author Marin Todorov, http://www.touch-code-magazine.com
  6. //
  7. // Copyright (c) 2012-2014 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. // The MIT License in plain English: http://www.touch-code-magazine.com/JSONModel/MITLicense
  15. #import "JSONKeyMapper.h"
  16. @interface JSONKeyMapper()
  17. @property (nonatomic, strong) NSMutableDictionary *toModelMap;
  18. @property (nonatomic, strong) NSMutableDictionary *toJSONMap;
  19. @end
  20. @implementation JSONKeyMapper
  21. -(instancetype)init
  22. {
  23. self = [super init];
  24. if (self) {
  25. //initialization
  26. self.toModelMap = [NSMutableDictionary dictionary];
  27. self.toJSONMap = [NSMutableDictionary dictionary];
  28. }
  29. return self;
  30. }
  31. -(instancetype)initWithJSONToModelBlock:(JSONModelKeyMapBlock)toModel
  32. modelToJSONBlock:(JSONModelKeyMapBlock)toJSON
  33. {
  34. self = [self init];
  35. if (self) {
  36. __weak JSONKeyMapper *myself = self;
  37. //the json to model convertion block
  38. _JSONToModelKeyBlock = ^NSString*(NSString* keyName) {
  39. //try to return cached transformed key
  40. if (myself.toModelMap[keyName]) return myself.toModelMap[keyName];
  41. //try to convert the key, and store in the cache
  42. NSString* result = toModel(keyName);
  43. myself.toModelMap[keyName] = result;
  44. return result;
  45. };
  46. _modelToJSONKeyBlock = ^NSString*(NSString* keyName) {
  47. //try to return cached transformed key
  48. if (myself.toJSONMap[keyName]) return myself.toJSONMap[keyName];
  49. //try to convert the key, and store in the cache
  50. NSString* result = toJSON(keyName);
  51. myself.toJSONMap[keyName] = result;
  52. return result;
  53. };
  54. }
  55. return self;
  56. }
  57. -(instancetype)initWithDictionary:(NSDictionary*)map
  58. {
  59. self = [super init];
  60. if (self) {
  61. //initialize
  62. NSMutableDictionary* userToModelMap = [NSMutableDictionary dictionaryWithDictionary: map];
  63. NSMutableDictionary* userToJSONMap = [NSMutableDictionary dictionaryWithObjects:map.allKeys forKeys:map.allValues];
  64. _JSONToModelKeyBlock = ^NSString*(NSString* keyName) {
  65. NSString* result = [userToModelMap valueForKeyPath: keyName];
  66. return result?result:keyName;
  67. };
  68. _modelToJSONKeyBlock = ^NSString*(NSString* keyName) {
  69. NSString* result = [userToJSONMap valueForKeyPath: keyName];
  70. return result?result:keyName;
  71. };
  72. }
  73. return self;
  74. }
  75. -(NSString*)convertValue:(NSString*)value isImportingToModel:(BOOL)importing
  76. {
  77. return !importing?_JSONToModelKeyBlock(value):_modelToJSONKeyBlock(value);
  78. }
  79. +(instancetype)mapperFromUnderscoreCaseToCamelCase
  80. {
  81. JSONModelKeyMapBlock toModel = ^ NSString* (NSString* keyName) {
  82. //bail early if no transformation required
  83. if ([keyName rangeOfString:@"_"].location==NSNotFound) return keyName;
  84. //derive camel case out of underscore case
  85. NSString* camelCase = [keyName capitalizedString];
  86. camelCase = [camelCase stringByReplacingOccurrencesOfString:@"_" withString:@""];
  87. camelCase = [camelCase stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[camelCase substringToIndex:1] lowercaseString] ];
  88. return camelCase;
  89. };
  90. JSONModelKeyMapBlock toJSON = ^ NSString* (NSString* keyName) {
  91. NSMutableString* result = [NSMutableString stringWithString:keyName];
  92. NSRange upperCharRange = [result rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]];
  93. //handle upper case chars
  94. while ( upperCharRange.location!=NSNotFound) {
  95. NSString* lowerChar = [[result substringWithRange:upperCharRange] lowercaseString];
  96. [result replaceCharactersInRange:upperCharRange
  97. withString:[NSString stringWithFormat:@"_%@", lowerChar]];
  98. upperCharRange = [result rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]];
  99. }
  100. //handle numbers
  101. NSRange digitsRange = [result rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
  102. while ( digitsRange.location!=NSNotFound) {
  103. NSRange digitsRangeEnd = [result rangeOfString:@"\\D" options:NSRegularExpressionSearch range:NSMakeRange(digitsRange.location, result.length-digitsRange.location)];
  104. if (digitsRangeEnd.location == NSNotFound) {
  105. //spands till the end of the key name
  106. digitsRangeEnd = NSMakeRange(result.length, 1);
  107. }
  108. NSRange replaceRange = NSMakeRange(digitsRange.location, digitsRangeEnd.location - digitsRange.location);
  109. NSString* digits = [result substringWithRange:replaceRange];
  110. [result replaceCharactersInRange:replaceRange withString:[NSString stringWithFormat:@"_%@", digits]];
  111. digitsRange = [result rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet] options:kNilOptions range:NSMakeRange(digitsRangeEnd.location+1, result.length-digitsRangeEnd.location-1)];
  112. }
  113. return result;
  114. };
  115. return [[self alloc] initWithJSONToModelBlock:toModel
  116. modelToJSONBlock:toJSON];
  117. }
  118. +(instancetype)mapperFromUpperCaseToLowerCase
  119. {
  120. JSONModelKeyMapBlock toModel = ^ NSString* (NSString* keyName) {
  121. NSString*lowercaseString = [keyName lowercaseString];
  122. return lowercaseString;
  123. };
  124. JSONModelKeyMapBlock toJSON = ^ NSString* (NSString* keyName) {
  125. NSString *uppercaseString = [keyName uppercaseString];
  126. return uppercaseString;
  127. };
  128. return [[self alloc] initWithJSONToModelBlock:toModel
  129. modelToJSONBlock:toJSON];
  130. }
  131. @end