forked from jsonmodel/jsonmodel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONModel.m
More file actions
996 lines (784 loc) · 36.9 KB
/
JSONModel.m
File metadata and controls
996 lines (784 loc) · 36.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
//
// JSONModel.m
//
// @version 0.9.0
// @author Marin Todorov, http://www.touch-code-magazine.com
//
// Copyright (c) 2012-2013 Marin Todorov, Underplot ltd.
// This code is distributed under the terms and conditions of the MIT license.
//
// 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:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 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.
//
// The MIT License in plain English: http://www.touch-code-magazine.com/JSONModel/MITLicense
#if !__has_feature(objc_arc)
#error The JSONMOdel framework is ARC only, you can enable ARC on per file basis.
#endif
#import <objc/runtime.h>
#import "JSONModel.h"
#import "JSONModelClassProperty.h"
#import "JSONModelArray.h"
#pragma mark - associated objects names
static const char * kMapperObjectKey;
static const char * kClassPropertiesKey;
static const char * kClassRequiredPropertyNamesKey;
static const char * kIndexPropertyNameKey;
#pragma mark - class static variables
static NSArray* allowedJSONTypes = nil;
static NSArray* allowedPrimitiveTypes = nil;
static JSONValueTransformer* valueTransformer = nil;
#pragma mark - model cache
static JSONKeyMapper* globalKeyMapper = nil;
#pragma mark - JSONModel implementation
@implementation JSONModel
#pragma mark - initialization methods
+(void)load
{
static dispatch_once_t once;
dispatch_once(&once, ^{
// initialize all class static objects,
// which are common for ALL JSONModel subclasses
@autoreleasepool {
allowedJSONTypes = @[
[NSString class], [NSNumber class], [NSArray class], [NSDictionary class], [NSNull class], //immutable JSON classes
[NSMutableString class], [NSMutableArray class], [NSMutableDictionary class] //mutable JSON classes
];
allowedPrimitiveTypes = @[
@"BOOL", @"float", @"int", @"long", @"double", @"short",
//and some famous aliases
@"NSInteger", @"NSUInteger"
];
valueTransformer = [[JSONValueTransformer alloc] init];
}
});
}
-(void)__setup__
{
//if first instance of this model, generate the property list
if (!objc_getAssociatedObject(self.class, &kClassPropertiesKey)) {
[self __restrospectProperties];
}
//if there's a custom key mapper, store it in the associated object
id mapper = [[self class] keyMapper];
if ( mapper && !objc_getAssociatedObject(self.class, &kMapperObjectKey) ) {
objc_setAssociatedObject(
self.class,
&kMapperObjectKey,
mapper,
OBJC_ASSOCIATION_RETAIN // This is atomic
);
}
}
-(id)init
{
self = [super init];
if (self) {
//do initial class setup
[self __setup__];
}
return self;
}
-(id)initWithString:(NSString*)string error:(JSONModelError**)err
{
JSONModelError* initError = nil;
id objModel = [self initWithString:string usingEncoding:NSUTF8StringEncoding error:&initError];
if (initError && err) *err = initError;
return objModel;
}
-(id)initWithString:(NSString *)string usingEncoding:(NSStringEncoding)encoding error:(JSONModelError**)err
{
//check for nil input
if (!string) {
if (err) *err = [JSONModelError errorInputIsNil];
return nil;
}
//read the json
JSONModelError* initError = nil;
id obj = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:encoding]
options:kNilOptions
error:&initError];
if (initError) {
if (err) *err = [JSONModelError errorBadJSON];
return nil;
}
//init with dictionary
id objModel = [self initWithDictionary:obj error:&initError];
if (initError && err) *err = initError;
return objModel;
}
-(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err
{
//check for nil input
if (!dict) {
if (err) *err = [JSONModelError errorInputIsNil];
return nil;
}
//invalid input, just create empty instance
if (![dict isKindOfClass:[NSDictionary class]]) {
if (err) *err = [JSONModelError errorInvalidData];
return nil;
}
//create a class instance
self = [super init];
if (!self) {
//super init didn't succeed
if (err) *err = [JSONModelError errorModelIsInvalid];
return nil;
}
//do initial class setup, retrospect properties
[self __setup__];
//check if all required properties are present
NSArray* incomingKeysArray = [dict allKeys];
NSMutableSet* requiredProperties = [self __requiredPropertyNames];
NSSet* incomingKeys = [NSSet setWithArray: incomingKeysArray];
//get the model key mapper
JSONKeyMapper* keyMapper = objc_getAssociatedObject(self.class, &kMapperObjectKey);
//if no custom mapper, check for a global mapper
if (keyMapper==nil && globalKeyMapper!=nil) keyMapper = globalKeyMapper;
//transform the key names, if neccessary
if (keyMapper) {
NSMutableSet* transformedIncomingKeys = [NSMutableSet setWithCapacity: requiredProperties.count];
NSString* transformedName = nil;
//loop over the required properties list
for (NSString* requiredPropertyName in requiredProperties) {
//get the mapped key path
transformedName = keyMapper.modelToJSONKeyBlock(requiredPropertyName);
//chek if exists and if so, add to incoming keys
if ([dict valueForKeyPath:transformedName]) {
[transformedIncomingKeys addObject: requiredPropertyName];
}
}
//overwrite the raw incoming list with the mapped key names
incomingKeys = transformedIncomingKeys;
}
//check for missing input keys
if (![requiredProperties isSubsetOfSet:incomingKeys]) {
//get a list of the missing properties
[requiredProperties minusSet:incomingKeys];
//not all required properties are in - invalid input
JMLog(@"Incoming data was invalid [%@ initWithDictionary:]. Keys missing: %@", self.class, requiredProperties);
if (err) *err = [JSONModelError errorInvalidDataWithMissingKeys:requiredProperties];
return nil;
}
//not needed anymore
incomingKeys= nil;
requiredProperties= nil;
//loop over the incoming keys and set self's properties
for (JSONModelClassProperty* property in [self __properties__]) {
//convert key name ot model keys, if a mapper is provided
NSString* jsonKeyPath = property.name;
if (keyMapper) jsonKeyPath = keyMapper.modelToJSONKeyBlock( property.name );
//JMLog(@"keyPath: %@", jsonKeyPath);
//general check for data type compliance
id jsonValue = [dict valueForKeyPath: jsonKeyPath];
//check for Optional properties
if (jsonValue==nil && property.isOptional==YES) {
//skip this property, continue with next property
continue;
}
Class jsonValueClass = [jsonValue class];
BOOL isValueOfAllowedType = NO;
for (Class allowedType in allowedJSONTypes) {
if ( [jsonValueClass isSubclassOfClass: allowedType] ) {
isValueOfAllowedType = YES;
break;
}
}
if (isValueOfAllowedType==NO) {
//type not allowed
JMLog(@"Type %@ is not allowed in JSON.", NSStringFromClass(jsonValueClass));
if (err) *err = [JSONModelError errorInvalidData];
return nil;
}
//check if there's matching property in the model
if (property) {
// check for custom setter, than the model doesn't need to do any guessing
// how to read the property's value from JSON
if ([self __customSetValue:jsonValue forProperty:property]) {
//skip to next JSON key
continue;
};
// 0) handle primitives
if (property.type == nil && property.structName==nil) {
//generic setter
[self setValue:jsonValue forKey: property.name];
//skip directly to the next key
continue;
}
// 0.5) handle nils
if (isNull(jsonValue)) {
[self setValue:nil forKey: property.name];
continue;
}
// 1) check if property is itself a JSONModel
if ([[property.type class] isSubclassOfClass:[JSONModel class]]) {
//initialize the property's model, store it
NSError* initError = nil;
id value = [[property.type alloc] initWithDictionary: jsonValue error:&initError];
if (!value) {
if (initError && err) *err = [JSONModelError errorInvalidData];
return nil;
}
[self setValue:value forKey: property.name];
//for clarity, does the same without continue
continue;
} else {
// 2) check if there's a protocol to the property
// ) might or not be the case there's a built in transofrm for it
if (property.protocol) {
//JMLog(@"proto: %@", p.protocol);
jsonValue = [self __transform:jsonValue forProperty:property];
if (!jsonValue) {
if (err) *err = [JSONModelError errorInvalidData];
return nil;
}
}
// 3.1) handle matching standard JSON types
if (property.isStandardJSONType && [jsonValue isKindOfClass: property.type]) {
//mutable properties
if (property.isMutable) {
jsonValue = [jsonValue mutableCopy];
}
//set the property value
[self setValue:jsonValue forKey: property.name];
continue;
}
// 3.3) handle values to transform
if (
(![jsonValue isKindOfClass:property.type] && !isNull(jsonValue))
||
//the property is mutable
property.isMutable
) {
// searched around the web how to do this better
// but did not find any solution, maybe that's the best idea? (hardly)
Class sourceClass = [JSONValueTransformer classByResolvingClusterClasses:[jsonValue class]];
//JMLog(@"to type: [%@] from type: [%@] transformer: [%@]", p.type, sourceClass, selectorName);
//build a method selector for the property and json object classes
NSString* selectorName = [NSString stringWithFormat:@"%@From%@:",
(property.structName? property.structName : property.type), //target name
sourceClass]; //source name
SEL selector = NSSelectorFromString(selectorName);
//check if there's a transformer with that name
if ([valueTransformer respondsToSelector:selector]) {
//it's OK, believe me...
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
//transform the value
jsonValue = [valueTransformer performSelector:selector withObject:jsonValue];
#pragma clang diagnostic pop
[self setValue:jsonValue forKey: property.name];
} else {
// it's not a JSON data type, and there's no transformer for it
// if property type is not supported - that's a programmer mistaked -> exception
@throw [NSException exceptionWithName:@"Type not allowed"
reason:[NSString stringWithFormat:@"%@ type not supported for %@.%@", property.type, [self class], property.name]
userInfo:nil];
return nil;
}
} else {
// 3.4) handle "all other" cases (if any)
[self setValue:jsonValue forKey: property.name];
}
}
}
}
//run any custom model validation
NSError* validationError = nil;
BOOL doesModelDataValidate = [self validate:&validationError];
if (doesModelDataValidate == NO) {
if (err) *err = validationError;
return nil;
}
//model is valid! yay!
return self;
}
#pragma mark - property restrospection methods
//returns a set of the required keys for the model
-(NSMutableSet*)__requiredPropertyNames
{
//fetch the associated property names
NSMutableSet* classRequiredPropertyNames = objc_getAssociatedObject(self.class, &kClassRequiredPropertyNamesKey);
if (!classRequiredPropertyNames) {
classRequiredPropertyNames = [NSMutableSet set];
[[self __properties__] enumerateObjectsUsingBlock:^(JSONModelClassProperty* p, NSUInteger idx, BOOL *stop) {
if (!p.isOptional) [classRequiredPropertyNames addObject:p.name];
}];
//persist the list
objc_setAssociatedObject(
self.class,
&kClassRequiredPropertyNamesKey,
classRequiredPropertyNames,
OBJC_ASSOCIATION_RETAIN // This is atomic
);
}
return classRequiredPropertyNames;
}
//returns a list of the model's properties
-(NSArray*)__properties__
{
//fetch the associated object
NSDictionary* classProperties = objc_getAssociatedObject(self.class, &kClassPropertiesKey);
if (classProperties) return [classProperties allValues];
//if here, the class needs to retrospect itself
[self __setup__];
//return the property list
classProperties = objc_getAssociatedObject(self.class, &kClassPropertiesKey);
return [classProperties allValues];
}
//retrospects the class, get's a list of the class properties
-(void)__restrospectProperties
{
//JMLog(@"Retrospect class: %@", [self class]);
NSMutableDictionary* propertyIndex = [NSMutableDictionary dictionary];
//temp variables for the loops
Class class = [self class];
NSScanner* scanner = nil;
NSString* propertyType = nil;
// retrospect inherited properties up to the JSONModel class
while (class != [JSONModel class]) {
//JMLog(@"retrospecting: %@", NSStringFromClass(class));
unsigned int propertyCount;
objc_property_t *properties = class_copyPropertyList(class, &propertyCount);
//loop over the class properties
for (unsigned int i = 0; i < propertyCount; i++) {
JSONModelClassProperty* p = [[JSONModelClassProperty alloc] init];
//get property name
objc_property_t property = properties[i];
const char *propertyName = property_getName(property);
p.name = [NSString stringWithUTF8String:propertyName];
//JMLog(@"property: %@", p.name);
//get property attributes
const char *attrs = property_getAttributes(property);
NSString* propertyAttributes = [NSString stringWithUTF8String:attrs];
if ([propertyAttributes hasPrefix:@"Tc,"]) {
//mask BOOLs as structs so they can have custom convertors
p.structName = @"BOOL";
}
scanner = [NSScanner scannerWithString: propertyAttributes];
//JMLog(@"attr: %@", [NSString stringWithCString:attrs encoding:NSUTF8StringEncoding]);
[scanner scanUpToString:@"T" intoString: nil];
[scanner scanString:@"T" intoString:nil];
//check if the property is an instance of a class
if ([scanner scanString:@"@\"" intoString: &propertyType]) {
[scanner scanCharactersFromSet:[NSCharacterSet alphanumericCharacterSet]
intoString:&propertyType];
//JMLog(@"type: %@", propertyClassName);
p.type = NSClassFromString(propertyType);
p.isMutable = ([propertyType rangeOfString:@"Mutable"].location != NSNotFound);
p.isStandardJSONType = [allowedJSONTypes containsObject:p.type];
//read through the property protocols
while ([scanner scanString:@"<" intoString:NULL]) {
NSString* protocolName = nil;
[scanner scanUpToString:@">" intoString: &protocolName];
if ([protocolName isEqualToString:@"Optional"]) {
p.isOptional = YES;
} else if([protocolName isEqualToString:@"Index"]) {
p.isIndex = YES;
objc_setAssociatedObject(
self.class,
&kIndexPropertyNameKey,
p.name,
OBJC_ASSOCIATION_RETAIN // This is atomic
);
} else if([protocolName isEqualToString:@"ConvertOnDemand"]) {
p.convertsOnDemand = YES;
} else {
p.protocol = protocolName;
}
[scanner scanString:@">" intoString:NULL];
}
}
//check if the property is a structure
else if ([scanner scanString:@"{" intoString: &propertyType]) {
[scanner scanCharactersFromSet:[NSCharacterSet alphanumericCharacterSet]
intoString:&propertyType];
p.isStandardJSONType = NO;
p.structName = propertyType;
}
//the property must be a primitive
else {
//the property contains a primitive data type
[scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@","]
intoString:&propertyType];
//get the full name of the primitive type
propertyType = valueTransformer.primitivesNames[propertyType];
if (![allowedPrimitiveTypes containsObject:propertyType]) {
//type not allowed - programmer mistaked -> exception
@throw [NSException exceptionWithName:@"JSONModelProperty type not allowed"
reason:[NSString stringWithFormat:@"Property type of %@.%@ is not supported by JSONModel.", self.class, p.name]
userInfo:nil];
}
}
if([[self class] propertyIsOptional:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]]){
p.isOptional = YES;
}
//add the property object to the temp index
[propertyIndex setValue:p forKey:p.name];
}
free(properties);
//ascend to the super of the class
//(will do that until it reaches the root class - JSONModel)
class = [class superclass];
}
//finally store the property index in the static property index
objc_setAssociatedObject(
self.class,
&kClassPropertiesKey,
[propertyIndex copy],
OBJC_ASSOCIATION_RETAIN // This is atomic
);
}
#pragma mark - built-in transformer methods
//few built-in transformations
-(id)__transform:(id)value forProperty:(JSONModelClassProperty*)property
{
Class protocolClass = NSClassFromString(property.protocol);
if (!protocolClass) {
//no other protocols on arrays and dictionaries
//except JSONModel classes
if ([value isKindOfClass:[NSArray class]]) {
@throw [NSException exceptionWithName:@"Bad property protocol declaration"
reason:[NSString stringWithFormat:@"<%@> is not allowed JSONModel property protocol, and not a JSONModel class.", property.protocol]
userInfo:nil];
}
return value;
}
//if the protocol is actually a JSONModel class
if ([[protocolClass class] isSubclassOfClass:[JSONModel class]]) {
//check if it's a list of models
if ([property.type isSubclassOfClass:[NSArray class]]) {
if (property.convertsOnDemand) {
//on demand conversion
value = [[JSONModelArray alloc] initWithArray:value modelClass:[protocolClass class]];
} else {
//one shot conversion
value = [[protocolClass class] arrayOfModelsFromDictionaries: value];
}
}
//check if it's a dictionary of models
if ([property.type isSubclassOfClass:[NSDictionary class]]) {
NSMutableDictionary* res = [NSMutableDictionary dictionary];
JSONModelError* initErr = nil;
for (NSString* key in [value allKeys]) {
id obj = [[[protocolClass class] alloc] initWithDictionary:value[key] error:&initErr];
if (initErr) {
return nil;
}
[res setValue:obj forKey:key];
}
value = [NSDictionary dictionaryWithDictionary:res];
}
}
return value;
}
//built-in reverse transormations (export to JSON compliant objects)
-(id)__reverseTransform:(id)value forProperty:(JSONModelClassProperty*)property
{
Class protocolClass = NSClassFromString(property.protocol);
if (!protocolClass) return value;
//if the protocol is actually a JSONModel class
if ([[protocolClass class] isSubclassOfClass:[JSONModel class]]) {
//check if should export list of dictionaries
if (property.type == [NSArray class] || property.type == [NSMutableArray class]) {
NSMutableArray* tempArray = [NSMutableArray arrayWithCapacity: [(NSArray*)value count] ];
for (id<AbstractJSONModelProtocol> model in (NSArray*)value) {
if ([model respondsToSelector:@selector(toDictionary)]) {
[tempArray addObject: [model toDictionary]];
} else
[tempArray addObject: model];
}
return [tempArray copy];
}
//check if should export dictionary of dictionaries
if (property.type == [NSDictionary class] || property.type == [NSMutableDictionary class]) {
NSMutableDictionary* res = [NSMutableDictionary dictionary];
for (NSString* key in [(NSDictionary*)value allKeys]) {
id<AbstractJSONModelProtocol> model = value[key];
[res setValue: [model toDictionary] forKey: key];
}
return [NSDictionary dictionaryWithDictionary:res];
}
}
return value;
}
#pragma mark - custom transformations
-(BOOL)__customSetValue:(id<NSObject>)value forProperty:(JSONModelClassProperty*)property
{
if (property.setterType == kNotInspected) {
//check for a custom property setter method
NSString* ucfirstName = [property.name stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[property.name substringToIndex:1] uppercaseString]];
NSString* selectorName = [NSString stringWithFormat:@"set%@With%@:", ucfirstName,
[JSONValueTransformer classByResolvingClusterClasses:[value class]]
];
SEL customPropertySetter = NSSelectorFromString(selectorName);
//check if there's a custom selector like this
if (![self respondsToSelector: customPropertySetter]) {
property.setterType = kNo;
return NO;
}
//cache the custom setter selector
property.setterType = kCustom;
property.customSetter = customPropertySetter;
}
if (property.setterType==kCustom) {
//call the custom setter
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self performSelector:property.customSetter withObject:value];
#pragma clang diagnostic pop
return YES;
}
return NO;
}
-(BOOL)__customGetValue:(id<NSObject>*)value forProperty:(JSONModelClassProperty*)property
{
if (property.getterType == kNotInspected) {
//check for a custom property getter method
NSString* ucfirstName = [property.name stringByReplacingCharactersInRange: NSMakeRange(0,1)
withString: [[property.name substringToIndex:1] uppercaseString]];
NSString* selectorName = [NSString stringWithFormat:@"JSONObjectFor%@", ucfirstName];
SEL customPropertyGetter = NSSelectorFromString(selectorName);
if (![self respondsToSelector: customPropertyGetter]) {
property.getterType = kNo;
return NO;
}
property.getterType = kCustom;
property.customGetter = customPropertyGetter;
}
if (property.getterType==kCustom) {
//call the custom getter
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
*value = [self performSelector:property.customGetter withObject:nil];
#pragma clang diagnostic pop
return YES;
}
return NO;
}
#pragma mark - persistance
-(void)__createDictionariesForKeyPath:(NSString*)keyPath inDictionary:(NSMutableDictionary**)dict
{
//find if there's a dot left in the keyPath
NSUInteger dotLocation = [keyPath rangeOfString:@"."].location;
if (dotLocation==NSNotFound) return;
//inspect next level
NSString* nextHierarchyLevelKeyName = [keyPath substringToIndex: dotLocation];
NSDictionary* nextLevelDictionary = [*dict objectForKey:nextHierarchyLevelKeyName];
if (nextLevelDictionary==nil) {
//create non-existing next level here
nextLevelDictionary = [NSMutableDictionary dictionary];
}
//recurse levels
[self __createDictionariesForKeyPath:[keyPath substringFromIndex: dotLocation+1]
inDictionary:&nextLevelDictionary ];
//create the hierarchy level
[*dict setValue:nextLevelDictionary forKeyPath: nextHierarchyLevelKeyName];
}
//exports the model as a dictionary of JSON compliant objects
-(NSDictionary*)toDictionary
{
NSArray* properties = [self __properties__];
NSMutableDictionary* tempDictionary = [NSMutableDictionary dictionaryWithCapacity:properties.count];
id value;
//get the key mapper
JSONKeyMapper* keyMapper = objc_getAssociatedObject(self.class, &kMapperObjectKey);
//loop over all properties
for (JSONModelClassProperty* p in properties) {
//fetch key and value
NSString* keyPath = p.name;
value = [self valueForKey: p.name];
//convert the key name, if a key mapper exists
if (keyMapper) keyPath = keyMapper.modelToJSONKeyBlock(keyPath);
//JMLog(@"toDictionary[%@]->[%@] = '%@'", p.name, keyPath, value);
if ([keyPath rangeOfString:@"."].location != NSNotFound) {
//there are sub-keys, introduce dictionaries for them
[self __createDictionariesForKeyPath:keyPath inDictionary:&tempDictionary];
}
//check for custom getter
if ([self __customGetValue:&value forProperty:p]) {
//custom getter, all done
[tempDictionary setValue:value forKey:keyPath];
continue;
}
//export nil when they are not optional values as JSON null, so that the structure of the exported data
//is still valid if it's to be imported as a model again
if (isNull(value)) {
if (p.isOptional)
{
[tempDictionary removeObjectForKey:keyPath];
}
else
{
[tempDictionary setValue:[NSNull null] forKeyPath:keyPath];
}
continue;
}
//check if the property is another model
if ([value isKindOfClass:[JSONModel class]]) {
//recurse models
value = [(JSONModel*)value toDictionary];
[tempDictionary setValue:value forKeyPath: keyPath];
//for clarity
continue;
} else {
// 1) check for built-in transformation
if (p.protocol) {
value = [self __reverseTransform:value forProperty:p];
}
// 2) check for standard types OR 2.1) primitives
if (p.structName==nil && (p.isStandardJSONType || p.type==nil)) {
//generic get value
[tempDictionary setValue:value forKeyPath: keyPath];
continue;
}
// 3) try to apply a value transformer
if (YES) {
//create selector from the property's class name
NSString* selectorName = [NSString stringWithFormat:@"%@From%@:", @"JSONObject", p.type?p.type:p.structName];
SEL selector = NSSelectorFromString(selectorName);
//check if there's a transformer declared
if ([valueTransformer respondsToSelector:selector]) {
//it's OK, believe me...
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
value = [valueTransformer performSelector:selector withObject:value];
#pragma clang diagnostic pop
[tempDictionary setValue:value forKeyPath: keyPath];
} else {
//in this case most probably a custom property was defined in a model
//but no default reverse transofrmer for it
@throw [NSException exceptionWithName:@"Value transformer not found"
reason:[NSString stringWithFormat:@"[JSONValueTransformer %@] not found", selectorName]
userInfo:nil];
return nil;
}
}
}
}
return [tempDictionary copy];
}
//exports model to a dictionary and then to a JSON string
-(NSString*)toJSONString
{
NSData* jsonData = nil;
NSError* jsonError = nil;
@try {
NSDictionary* dict = [self toDictionary];
jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&jsonError];
}
@catch (NSException *exception) {
//this should not happen in properly design JSONModel
//usually means there was no reverse transformer for a custom property
JMLog(@"EXCEPTION: %@", exception.description);
return nil;
}
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
#pragma mark - import/export of lists
//loop over an NSArray of JSON objects and turn them into models
+(NSMutableArray*)arrayOfModelsFromDictionaries:(NSArray*)array
{
//bail early
if (isNull(array)) return nil;
//parse dictionaries to objects
NSMutableArray* list = [NSMutableArray arrayWithCapacity: [array count]];
JSONModelError* err = nil;
for (NSDictionary* d in array) {
id obj = [[self alloc] initWithDictionary: d error:&err];
if (!obj) return nil;
[list addObject: obj];
}
return list;
}
//loop over NSArray of models and export them to JSON objects
+(NSMutableArray*)arrayOfDictionariesFromModels:(NSArray*)array
{
//bail early
if (isNull(array)) return nil;
//convert to dictionaries
NSMutableArray* list = [NSMutableArray arrayWithCapacity: [array count]];
for (id<AbstractJSONModelProtocol> object in array) {
id obj = [object toDictionary];
if (!obj) return nil;
[list addObject: obj];
}
return list;
}
#pragma mark - custom comparison methods
-(NSString*)indexPropertyName
{
//custom getter for an associated object
return objc_getAssociatedObject(self.class, &kIndexPropertyNameKey);
}
-(BOOL)isEqual:(id)object
{
//bail early if different classes
if (![object isMemberOfClass:[self class]]) return NO;
if (self.indexPropertyName) {
//there's a defined ID property
id objectId = [object valueForKey: self.indexPropertyName];
return [[self valueForKey: self.indexPropertyName] isEqual:objectId];
}
//default isEqual implementation
return [super isEqual:object];
}
-(NSComparisonResult)compare:(id)object
{
if (self.indexPropertyName) {
id objectId = [object valueForKey: self.indexPropertyName];
if ([objectId respondsToSelector:@selector(compare:)]) {
return [[self valueForKey:self.indexPropertyName] compare:objectId];
}
}
//on purpose postponing the asserts for speed optimization
//these should not happen anyway in production conditions
NSAssert(self.indexPropertyName, @"Can't compare models with no <Index> property");
NSAssert1(NO, @"The <Index> property of %@ is not comparable class.", [self class]);
return kNilOptions;
}
- (NSUInteger)hash
{
if (self.indexPropertyName) {
return [self.indexPropertyName hash];
}
return [super hash];
}
#pragma mark - custom data validation
-(BOOL)validate:(NSError**)error
{
return YES;
}
#pragma mark - custom recursive description
//custom description method for debugging purposes
-(NSString*)description
{
NSMutableString* text = [NSMutableString stringWithFormat:@"<%@> \n", [self class]];
for (JSONModelClassProperty *p in [self __properties__]) {
id value = [self valueForKey:p.name];
NSString* valueDescription = (value)?[value description]:@"<nil>";
if (p.isStandardJSONType && ![value respondsToSelector:@selector(count)] && [valueDescription length]>60 && !p.convertsOnDemand) {
//cap description for longer values
valueDescription = [NSString stringWithFormat:@"%@...", [valueDescription substringToIndex:59]];
}
valueDescription = [valueDescription stringByReplacingOccurrencesOfString:@"\n" withString:@"\n "];
[text appendFormat:@" [%@]: %@\n", p.name, valueDescription];
}
[text appendFormat:@"</%@>", [self class]];
return text;
}
#pragma mark - key mapping
+(JSONKeyMapper*)keyMapper
{
return nil;
}
+(void)setGlobalKeyMapper:(JSONKeyMapper*)globalKeyMapperParam
{
globalKeyMapper = globalKeyMapperParam;
}
+(BOOL)propertyIsOptional:(NSString*)propertyName{
return NO;
}
@end