NSObject+YYModel.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. //
  2. // NSObject+YYModel.h
  3. // YYModel <https://github.com/ibireme/YYModel>
  4. //
  5. // Created by ibireme on 15/5/10.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import <Foundation/Foundation.h>
  12. /**
  13. Provide some data-model method:
  14. * Convert json to any object, or convert any object to json.
  15. * Set object properties with a key-value dictionary (like KVC).
  16. * Implementations of `NSCoding`, `NSCopying`, `-hash` and `-isEqual:`.
  17. See `YYModel` protocol for custom methods.
  18. Sample Code:
  19. ********************** json convertor *********************
  20. @interface YYAuthor : NSObject
  21. @property (nonatomic, strong) NSString *name;
  22. @property (nonatomic, assign) NSDate *birthday;
  23. @end
  24. @implementation YYAuthor
  25. @end
  26. @interface YYBook : NSObject
  27. @property (nonatomic, copy) NSString *name;
  28. @property (nonatomic, assign) NSUInteger pages;
  29. @property (nonatomic, strong) YYAuthor *author;
  30. @end
  31. @implementation YYBook
  32. @end
  33. int main() {
  34. // create model from json
  35. YYBook *book = [YYBook yy_modelWithJSON:@"{\"name\": \"Harry Potter\", \"pages\": 256, \"author\": {\"name\": \"J.K.Rowling\", \"birthday\": \"1965-07-31\" }}"];
  36. // convert model to json
  37. NSString *json = [book yy_modelToJSONString];
  38. // {"author":{"name":"J.K.Rowling","birthday":"1965-07-31T00:00:00+0000"},"name":"Harry Potter","pages":256}
  39. }
  40. ********************** Coding/Copying/hash/equal *********************
  41. @interface YYShadow :NSObject <NSCoding, NSCopying>
  42. @property (nonatomic, copy) NSString *name;
  43. @property (nonatomic, assign) CGSize size;
  44. @end
  45. @implementation YYShadow
  46. - (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
  47. - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }
  48. - (id)copyWithZone:(NSZone *)zone { return [self yy_modelCopy]; }
  49. - (NSUInteger)hash { return [self yy_modelHash]; }
  50. - (BOOL)isEqual:(id)object { return [self yy_modelIsEqual:object]; }
  51. @end
  52. */
  53. @interface NSObject (YYModel)
  54. /**
  55. Creates and returns a new instance of the receiver from a json.
  56. This method is thread-safe.
  57. @param json A json object in `NSDictionary`, `NSString` or `NSData`.
  58. @return A new instance created from the json, or nil if an error occurs.
  59. */
  60. + (instancetype)yy_modelWithJSON:(id)json;
  61. /**
  62. Creates and returns a new instance of the receiver from a key-value dictionary.
  63. This method is thread-safe.
  64. @param dictionary A key-value dictionary mapped to the instance's properties.
  65. Any invalid key-value pair in dictionary will be ignored.
  66. @return A new instance created from the dictionary, or nil if an error occurs.
  67. @discussion The key in `dictionary` will mapped to the reciever's property name,
  68. and the value will set to the property. If the value's type does not match the
  69. property, this method will try to convert the value based on these rules:
  70. `NSString` or `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger...
  71. `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd".
  72. `NSString` -> NSURL.
  73. `NSValue` -> struct or union, such as CGRect, CGSize, ...
  74. `NSString` -> SEL, Class.
  75. */
  76. + (instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary;
  77. /**
  78. Set the receiver's properties with a json object.
  79. @discussion Any invalid data in json will be ignored.
  80. @param json A json object of `NSDictionary`, `NSString` or `NSData`, mapped to the
  81. receiver's properties.
  82. @return Whether succeed.
  83. */
  84. - (BOOL)yy_modelSetWithJSON:(id)json;
  85. /**
  86. Set the receiver's properties with a key-value dictionary.
  87. @param dic A key-value dictionary mapped to the receiver's properties.
  88. Any invalid key-value pair in dictionary will be ignored.
  89. @discussion The key in `dictionary` will mapped to the reciever's property name,
  90. and the value will set to the property. If the value's type doesn't match the
  91. property, this method will try to convert the value based on these rules:
  92. `NSString`, `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger...
  93. `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd".
  94. `NSString` -> NSURL.
  95. `NSValue` -> struct or union, such as CGRect, CGSize, ...
  96. `NSString` -> SEL, Class.
  97. @return Whether succeed.
  98. */
  99. - (BOOL)yy_modelSetWithDictionary:(NSDictionary *)dic;
  100. /**
  101. Generate a json object from the receiver's properties.
  102. @return A json object in `NSDictionary` or `NSArray`, or nil if an error occurs.
  103. See [NSJSONSerialization isValidJSONObject] for more information.
  104. @discussion Any of the invalid property is ignored.
  105. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it just convert
  106. the inner object to json object.
  107. */
  108. - (id)yy_modelToJSONObject;
  109. /**
  110. Generate a json string's data from the receiver's properties.
  111. @return A json string's data, or nil if an error occurs.
  112. @discussion Any of the invalid property is ignored.
  113. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it will also convert the
  114. inner object to json string.
  115. */
  116. - (NSData *)yy_modelToJSONData;
  117. /**
  118. Generate a json string from the receiver's properties.
  119. @return A json string, or nil if an error occurs.
  120. @discussion Any of the invalid property is ignored.
  121. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it will also convert the
  122. inner object to json string.
  123. */
  124. - (NSString *)yy_modelToJSONString;
  125. /**
  126. Copy a instance with the receiver's properties.
  127. @return A copied instance, or nil if an error occurs.
  128. */
  129. - (id)yy_modelCopy;
  130. /**
  131. Encode the receiver's properties to a coder.
  132. @param aCoder An archiver object.
  133. */
  134. - (void)yy_modelEncodeWithCoder:(NSCoder *)aCoder;
  135. /**
  136. Decode the receiver's properties from a decoder.
  137. @param aDecoder An archiver object.
  138. @return self
  139. */
  140. - (id)yy_modelInitWithCoder:(NSCoder *)aDecoder;
  141. /**
  142. Get a hash code with the receiver's properties.
  143. @return Hash code.
  144. */
  145. - (NSUInteger)yy_modelHash;
  146. /**
  147. Compares the receiver with another object for equality, based on properties.
  148. @param model Another object.
  149. @return `YES` if the reciever is equal to the object, otherwise `NO`.
  150. */
  151. - (BOOL)yy_modelIsEqual:(id)model;
  152. /**
  153. Description method for debugging purposes based on properties.
  154. @return A string that describes the contents of the receiver.
  155. */
  156. - (NSString *)yy_modelDescription;
  157. @end
  158. /**
  159. Provide some data-model method for NSArray.
  160. */
  161. @interface NSArray (YYModel)
  162. /**
  163. Creates and returns an array from a json-array.
  164. This method is thread-safe.
  165. @param cls The instance's class in array.
  166. @param json A json array of `NSArray`, `NSString` or `NSData`.
  167. Example: [{"name","Mary"},{name:"Joe"}]
  168. @return A array, or nil if an error occurs.
  169. */
  170. + (NSArray *)yy_modelArrayWithClass:(Class)cls json:(id)json;
  171. @end
  172. /**
  173. Provide some data-model method for NSDictionary.
  174. */
  175. @interface NSDictionary (YYModel)
  176. /**
  177. Creates and returns a dictionary from a json.
  178. This method is thread-safe.
  179. @param cls The value instance's class in dictionary.
  180. @param json A json dictionary of `NSDictionary`, `NSString` or `NSData`.
  181. Example: {"user1":{"name","Mary"}, "user2": {name:"Joe"}}
  182. @return A array, or nil if an error occurs.
  183. */
  184. + (NSDictionary *)yy_modelDictionaryWithClass:(Class)cls json:(id)json;
  185. @end
  186. /**
  187. If the default model transform does not fit to your model class, implement one or
  188. more method in this protocol to change the default key-value transform process.
  189. There's no need to add '<YYModel>' to your class header.
  190. */
  191. @protocol YYModel <NSObject>
  192. @optional
  193. /**
  194. Custom property mapper.
  195. @discussion If the key in JSON/Dictionary does not match to the model's property name,
  196. implements this method and returns the additional mapper.
  197. Example:
  198. json:
  199. {
  200. "n":"Harry Pottery",
  201. "p": 256,
  202. "ext" : {
  203. "desc" : "A book written by J.K.Rowling."
  204. },
  205. "ID" : 100010
  206. }
  207. model:
  208. @interface YYBook : NSObject
  209. @property NSString *name;
  210. @property NSInteger page;
  211. @property NSString *desc;
  212. @property NSString *bookID;
  213. @end
  214. @implementation YYBook
  215. + (NSDictionary *)modelCustomPropertyMapper {
  216. return @{@"name" : @"n",
  217. @"page" : @"p",
  218. @"desc" : @"ext.desc",
  219. @"bookID": @[@"id", @"ID", @"book_id"]};
  220. }
  221. @end
  222. @return A custom mapper for properties.
  223. */
  224. + (NSDictionary *)modelCustomPropertyMapper;
  225. /**
  226. The generic class mapper for container properties.
  227. @discussion If the property is a container object, such as NSArray/NSSet/NSDictionary,
  228. implements this method and returns a property->class mapper, tells which kind of
  229. object will be add to the array/set/dictionary.
  230. Example:
  231. @class YYShadow, YYBorder, YYAttachment;
  232. @interface YYAttributes
  233. @property NSString *name;
  234. @property NSArray *shadows;
  235. @property NSSet *borders;
  236. @property NSDictionary *attachments;
  237. @end
  238. @implementation YYAttributes
  239. + (NSDictionary *)modelContainerPropertyGenericClass {
  240. return @{@"shadows" : [YYShadow class],
  241. @"borders" : YYBorder.class,
  242. @"attachments" : @"YYAttachment" };
  243. }
  244. @end
  245. @return A class mapper.
  246. */
  247. + (NSDictionary *)modelContainerPropertyGenericClass;
  248. /**
  249. If you need to create instances of different classes during json->object transform,
  250. use the method to choose custom class based on dictionary data.
  251. @discussion If the model implements this method, it will be called to determine resulting class
  252. during `+modelWithJSON:`, `+modelWithDictionary:`, conveting object of properties of parent objects
  253. (both singular and containers via `+modelContainerPropertyGenericClass`).
  254. Example:
  255. @class YYCircle, YYRectangle, YYLine;
  256. @implementation YYShape
  257. + (Class)modelCustomClassForDictionary:(NSDictionary*)dictionary {
  258. if (dictionary[@"radius"] != nil) {
  259. return [YYCircle class];
  260. } else if (dictionary[@"width"] != nil) {
  261. return [YYRectangle class];
  262. } else if (dictionary[@"y2"] != nil) {
  263. return [YYLine class];
  264. } else {
  265. return [self class];
  266. }
  267. }
  268. @end
  269. @param dictionary The json/kv dictionary.
  270. @return Class to create from this dictionary, `nil` to use current class.
  271. */
  272. + (Class)modelCustomClassForDictionary:(NSDictionary*)dictionary;
  273. /**
  274. All the properties in blacklist will be ignored in model transform process.
  275. Returns nil to ignore this feature.
  276. @return An array of property's name (Array<NSString>).
  277. */
  278. + (NSArray *)modelPropertyBlacklist;
  279. /**
  280. If a property is not in the whitelist, it will be ignored in model transform process.
  281. Returns nil to ignore this feature.
  282. @return An array of property's name (Array<NSString>).
  283. */
  284. + (NSArray *)modelPropertyWhitelist;
  285. /**
  286. If the default json-to-model transform does not fit to your model object, implement
  287. this method to do additional process. You can also use this method to validate the
  288. model's properties.
  289. @discussion If the model implements this method, it will be called at the end of
  290. `+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`.
  291. If this method returns NO, the transform process will ignore this model.
  292. @param dic The json/kv dictionary.
  293. @return Returns YES if the model is valid, or NO to ignore this model.
  294. */
  295. - (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic;
  296. /**
  297. If the default model-to-json transform does not fit to your model class, implement
  298. this method to do additional process. You can also use this method to validate the
  299. json dictionary.
  300. @discussion If the model implements this method, it will be called at the end of
  301. `-modelToJSONObject` and `-modelToJSONString`.
  302. If this method returns NO, the transform process will ignore this json dictionary.
  303. @param dic The json dictionary.
  304. @return Returns YES if the model is valid, or NO to ignore this model.
  305. */
  306. - (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic;
  307. @end