-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMSJsonKit.mm
More file actions
531 lines (462 loc) · 19.9 KB
/
MSJsonKit.mm
File metadata and controls
531 lines (462 loc) · 19.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
//
// MSJsonKit.m
//
//
// Created by Minster on 14/10/20.
//
//
#import "MSJsonKit.h"
#import "objc/runtime.h"
static NSString *re = @"(?<=T@\")(.*)(?=\",)";
static NSString *ignorePropNames = @"hash, superclass, description, debugDescription"; //当类实现协议后会自动添加以上四个属性到当前类中,特别是superclass迭代很多十分巨大会递归到死
static NSString *boolClassNameContain = @"TB";
static NSString *objClassNameContain = @"NS";
static BOOL sShouldLog = YES;
@implementation MSJsonKit
/**
* obj 转 json
* @param obj
* @param jsonAddr
*/
+(void)objToJson: (id)obj out: (NSMutableString **)jsonAddr withKey: (NSString *)key baseClass: (Class)baseClass preKey: (NSString *)preKey {
NSMutableString *json = *jsonAddr;
//初始化json
if (json == nil) {
json = [[NSMutableString alloc] init];
}
//是否有额外key
BOOL flag = false;
if (key != nil) {
if (json.length == 0) {
[json appendFormat: @"{\"%@\":", key];
flag = true;
} else {
[json appendFormat: @"\"%@\":", key];
}
}
if (obj == nil) {
//如果为空
[json appendString: [MSJsonKit getNullJsonWithKey: nil baseClass: baseClass preKey: preKey]];
} else if ([obj isKindOfClass: [NSArray class]]) {
//如果是数组
[json appendString: @"["];
NSArray *arr = (NSArray *)obj;
for (int i = 0; i < arr.count; i++) {
if (i != 0) {
[json appendString: @","];
}
[MSJsonKit objToJson: arr[i] out: &json withKey: nil baseClass: [obj class] preKey: preKey];
}
[json appendString: @"]"];
} else if ([obj isKindOfClass: [NSDictionary class]]) {
//如果是字典
[json appendString: @"{"];
int i = 0;
NSDictionary *o = obj;
for (NSString *keyName in o.allKeys) {
if (i != 0) {
[json appendString: @","];
}
[MSJsonKit objToJson: obj[keyName] out: &json withKey: keyName baseClass: [obj class] preKey: keyName];
i++;
}
[json appendString: @"}"];
} else if ([obj isKindOfClass: [NSString class]]) {
//如果是字符串
[json appendString: [MSJsonKit getStringJson: (NSString *)obj withKey: nil baseClass: baseClass preKey: preKey]];
} else if ([obj isKindOfClass: [NSNumber class]]) {
//如果是数字
[json appendString: [MSJsonKit getNumberJson: (NSNumber *)obj withKey: nil baseClass: baseClass preKey: preKey]];
} else if ([obj isKindOfClass: [NSDate class]]) {
//如果是日期
[json appendString: [MSJsonKit getDateJson: (NSDate *)obj withKey: nil baseClass: baseClass preKey: preKey]];
} else if ([obj isKindOfClass: [NSNull class]]) {
//如果为空类
[json appendString: [MSJsonKit getNullJsonWithKey: nil baseClass: baseClass preKey: preKey]];
} else if ([obj isKindOfClass: [NSObject class]]) {
//如果是一个自定义类
[json appendString: @"{"];
unsigned int outCount;
objc_property_t *props = class_copyPropertyList([obj class], &outCount);
int j = 0;
for (int i = 0; i < outCount; i++) {
objc_property_t prop = props[i];
NSString *propName = [[NSString alloc] initWithCString: property_getName(prop) encoding: NSUTF8StringEncoding];
if ([ignorePropNames rangeOfString: propName].location != NSNotFound) {
continue;
}
if ([[obj class] conformsToProtocol: @protocol(MSJsonSerializing)] && [[obj class] respondsToSelector: @selector(toJsonIgnoreKey)]) {
NSArray *tjika = [[obj class] toJsonIgnoreKey];
if ([tjika containsObject: propName]) {
continue;
}
}
if (j != 0) {
[json appendString: @","];
}
j++;
id value = [obj valueForKey: propName];
NSString *jsonKeyName = [NSString stringWithString: propName];
if ([[obj class] conformsToProtocol: @protocol(MSJsonSerializing)]) {
NSDictionary *jsonKeyPathsOfProp = [[obj class] jsonKeyPathsByPropertyKey];
if (jsonKeyPathsOfProp != nil && [[jsonKeyPathsOfProp allKeys] containsObject: propName]) {
jsonKeyName = [jsonKeyPathsOfProp objectForKey: propName];
}
}
[MSJsonKit objToJson: value out: &json withKey: jsonKeyName baseClass: [obj class] preKey: propName];
#ifdef DEBUG
// NSLog(@"key: %@", propName);
#endif
}
delete [] props;
[json appendString: @"}"];
}
if (flag == true) {
[json appendString: @"}"];
}
*jsonAddr = json;
}
/**
* obj 转 json
*
* @param obj obj
* @param key key
*/
+(NSString *)objToJson: (id)obj withKey: (NSString *)key {
if (obj == nil) {
return nil;
}
NSMutableString *json = nil;
[MSJsonKit objToJson: obj out: &json withKey: key baseClass: [obj class] preKey: key];
#ifdef DEBUG
if (sShouldLog) {
NSLog(@"json:\n%@", json);
}
#endif
return json;
}
/**
* json 转 obj
* @param json
* @param mclass
* @result (id)
*/
+(id)jsonToObj: (NSString *)json asClass: (Class)mclass {
if (json == nil) {
return nil;
}
return [MSJsonKit jsonToObj: json asClass: mclass WithKeyClass: nil];
}
/**
* json 转 obj
* @param json
* @param mclass
* @param keyClass
* @result (id)
*/
+(id)jsonToObj:(NSString *)json asClass:(Class)mclass WithKeyClass: (NSDictionary *) keyClass {
//id obj = nil;
//初始化对象
//obj = [[mclass alloc] init];
//将json转化为字典
NSError *error = nil;
id jsonObj = [NSJSONSerialization JSONObjectWithData: [json dataUsingEncoding: NSUTF8StringEncoding] options: kNilOptions error: &error];
if (jsonObj == nil) {
return jsonObj;
}
#ifdef DEBUG
if (sShouldLog) {
NSLog(@"JSON:\n%@", jsonObj);
}
#endif
@try {
return [MSJsonKit jsonObjToObj: jsonObj asClass: mclass WithKeyClass: keyClass ForKey: @"msroot" baseClass: mclass];
}
@catch (NSException *exception) {
return nil;
}
@finally {
}
}
/**
* jsonObj 转 obj
* @param json 需转化的json字符串
* @param mclass 需转化成的objc类
* @param keyClass 如果有某个objc类属性为NSArray或者NSDictionay, 可以传入@{@"asdf"(该属性键): (数组每项的类型或者字典每个值的类型),....},否则传nil
*
* @result (id) 转化后的objc对象
*/
+(id)jsonObjToObj: (id)jsonObj asClass:(Class)mclass WithKeyClass: (NSDictionary *) keyClass {
if (jsonObj == nil) {
return jsonObj;
}
#ifdef DEBUG
if (sShouldLog) {
NSLog(@"JSON:\n%@", jsonObj);
}
#endif
@try {
return [MSJsonKit jsonObjToObj: jsonObj asClass: mclass WithKeyClass: keyClass ForKey: @"msroot" baseClass: mclass];
}
@catch (NSException *exception) {
return nil;
}
@finally {
}
}
/**
* jsonObj 转 obj
* @param json 需转化的json字符串
* @param mclass 需转化成的objc类
* @param keyClass 如果有某个objc类属性为NSArray或者NSDictionay, 可以传入@{@"asdf"(该属性键): (数组每项的类型或者字典每个值的类型),....},否则传nil
*
* @result (id) 转化后的objc对象
*/
+(id)jsonObjToObj: (id)jsonObj asClass:(Class)mclass {
if (jsonObj == nil) {
return jsonObj;
}
#ifdef DEBUG
if (sShouldLog) {
NSLog(@"JSON:\n%@", jsonObj);
}
#endif
@try {
return [MSJsonKit jsonObjToObj: jsonObj asClass: mclass WithKeyClass: nil ForKey: @"msroot" baseClass: mclass];
}
@catch (NSException *exception) {
return nil;
}
@finally {
}
}
+(id)jsonObjToObj: (id)jsonObj asClass:(Class)mclass WithKeyClass: (NSDictionary *) keyClass ForKey:(NSString *)keyName baseClass: (Class)baseClass {
id obj;
if ([baseClass conformsToProtocol: @protocol(MSJsonSerializing)] && [baseClass respondsToSelector: @selector(keyClass)]) {
NSDictionary *keyClassDic = [baseClass keyClass];
if (keyClassDic != nil && keyClassDic.allKeys.count > 0) {
keyClass = keyClassDic;
}
}
if (jsonObj != nil) {
if ([mclass isSubclassOfClass: [NSDictionary class]] && [jsonObj isKindOfClass: [NSDictionary class]]) {
if (keyClass != nil && [keyClass.allKeys containsObject: keyName]) {
mclass = (Class)(keyClass[keyName]);
}
NSDictionary *dic = (NSDictionary *)jsonObj;
obj = [[NSMutableDictionary alloc] init];
for (NSString *key in dic) {
Class tclass = mclass;
if ([dic[key] isKindOfClass: [NSArray class]]) { //[dic[key] isKindOfClass: [NSDictionary class]] ||
tclass = [dic[key] class];
}
if (keyClass != nil && [keyClass.allKeys containsObject: key]) {
tclass = (Class)(keyClass[key]);
}
id value = [MSJsonKit jsonObjToObj: dic[key] asClass: tclass WithKeyClass: keyClass ForKey:keyName baseClass: tclass];
if (value && ![value isKindOfClass: [NSNull class]]) {
[obj setValue: value forKey: key];
}
}
} else if ([mclass isSubclassOfClass: [NSArray class]] && [jsonObj isKindOfClass: [NSArray class]]) {
if (keyClass !=nil && [keyClass.allKeys containsObject: keyName]) {
mclass = (Class)(keyClass[keyName]);
}
NSArray *arr = (NSArray *)jsonObj;
obj = [[NSMutableArray alloc] init];
for (int j = 0; j < arr.count; j++) {
Class tclass = mclass;
if ([arr[j] isKindOfClass: [NSArray class]]) { //[arr[j] isKindOfClass: [NSDictionary class]] ||
tclass = [arr[j] class];
}
id value = [MSJsonKit jsonObjToObj: arr[j] asClass: tclass WithKeyClass: keyClass ForKey:keyName baseClass: tclass];
if (value && ![value isKindOfClass: [NSNull class]]) {
[obj addObject: value];
}
}
} else if ([mclass isSubclassOfClass: [NSDate class]]) {
if ([jsonObj isKindOfClass: [NSNull class]]) {
obj = nil;
} else {
if ([baseClass conformsToProtocol: @protocol(MSJsonSerializing)] && [baseClass respondsToSelector: @selector(jsonValueConverter)]) {
NSDictionary *cvtDic = [baseClass jsonValueConverter];
if (cvtDic != nil && [cvtDic.allKeys containsObject: keyName]) {
obj = ((NSObject *(^)(NSObject *time))[cvtDic objectForKey: keyName])(jsonObj);
} else {
obj = [NSDate dateWithTimeIntervalSince1970: [((NSNumber *)jsonObj) doubleValue]/1000];
}
} else {
obj = [NSDate dateWithTimeIntervalSince1970: [((NSNumber *)jsonObj) doubleValue]/1000];
}
}
} else if (![mclass isSubclassOfClass: [NSString class]] &&
![mclass isSubclassOfClass: [NSNumber class]] &&
![mclass isSubclassOfClass: [NSDictionary class]] &&
![mclass isSubclassOfClass: [NSArray class]] &&
![mclass isSubclassOfClass: [NSDate class]] &&
[mclass isSubclassOfClass: [NSObject class]]) {
NSDictionary *dic = nil;
if ([jsonObj isKindOfClass: [NSDictionary class]]) {
dic = (NSDictionary *)jsonObj;
} else if ([jsonObj isKindOfClass: [NSString class]]) {
NSError *error = nil;
dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData: [jsonObj dataUsingEncoding: NSUTF8StringEncoding] options: kNilOptions error: &error];
if (error != nil) {
if ([jsonObj isKindOfClass: [NSNull class]]) {
obj = nil;
} else {
obj = jsonObj;
}
return obj;
}
} else {
if ([jsonObj isKindOfClass: [NSNull class]]) {
obj = nil;
} else {
obj = jsonObj;
}
return obj;
}
obj = [[mclass alloc] init];
//遍历属性
unsigned int outCount;
objc_property_t *props = class_copyPropertyList(mclass, &outCount);
for (int i = 0; i < outCount; i++) {
objc_property_t prop = props[i];
NSString *propName = [[NSString alloc] initWithCString: property_getName(prop) encoding: NSUTF8StringEncoding];
if ([ignorePropNames rangeOfString: propName].location != NSNotFound) {
continue;
}
NSString *dicPropName = [NSString stringWithString: propName];
if ([[obj class] conformsToProtocol: @protocol(MSJsonSerializing)]) {
NSDictionary *jsonKeyPathsOfProp = [[obj class] jsonKeyPathsByPropertyKey];
if (jsonKeyPathsOfProp != nil && [[jsonKeyPathsOfProp allKeys] containsObject: propName]) {
dicPropName = [jsonKeyPathsOfProp objectForKey: propName];
}
}
NSString *propAttr = [[NSString alloc] initWithCString: property_getAttributes(prop) encoding: NSUTF8StringEncoding];
if (propName == nil) {
continue;
} else {
NSRange range = [propAttr rangeOfString: re options: NSRegularExpressionSearch];
if ([dic.allKeys containsObject: dicPropName]) {
if (range.length != 0) {
NSString *propClassName = [propAttr substringWithRange: range];
#ifdef DEBUG
// NSLog(@"propClassName: %@", propClassName);
#endif
if ([dic.allKeys containsObject: dicPropName]) {
Class propClass = objc_getClass([propClassName UTF8String]);
id value = [MSJsonKit jsonObjToObj: dic[dicPropName] asClass: propClass WithKeyClass: keyClass ForKey: propName baseClass: mclass];
if (value && ![value isKindOfClass: [NSNull class]]) {
[obj setValue: value forKey: propName];
}
}
} else {
if (dic[dicPropName] == nil) {
} else {
id value = [MSJsonKit jsonObjToObj: dic[dicPropName] asClass: [NSNumber class] WithKeyClass: keyClass ForKey: propName baseClass: mclass];
if (value && ![value isKindOfClass: [NSNull class]]) {
[obj setValue: value forKey: propName];
}
}
}
}
}
}
delete [] props;
} else if ([jsonObj isKindOfClass: [NSNull class]]) {
obj = nil;
} else {
if ([baseClass conformsToProtocol: @protocol(MSJsonSerializing)] && [baseClass respondsToSelector: @selector(jsonValueConverter)]) {
NSDictionary *cvtDic = [baseClass jsonValueConverter];
if (cvtDic != nil && [cvtDic.allKeys containsObject: keyName]) {
obj = ((id(^)(id obj))[cvtDic objectForKey: keyName])(jsonObj);
} else {
obj = jsonObj;
}
} else {
obj = jsonObj;
}
}
}
if (obj == nil) {
return [[NSNull alloc] init];
}
return obj;
}
+(NSString *)getStringJson: (NSString *)str withKey: (NSString *)key baseClass: (Class)baseClass preKey: (NSString *)preKey {
NSString *json = nil;
if ([baseClass conformsToProtocol: @protocol(MSJsonSerializing)] && [baseClass respondsToSelector: @selector(objcValueConverter)]) {
NSDictionary *cvtDic = [baseClass objcValueConverter];
if (cvtDic != nil && [cvtDic.allKeys containsObject: preKey]) {
json = ((NSString *(^)(NSObject *obj))[cvtDic objectForKey: preKey])(str);
} else {
json = [NSString stringWithFormat: @"\"%@\"", [str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]];
}
} else {
json = [NSString stringWithFormat: @"\"%@\"", [str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]];
}
if (key == nil) {
return json;
}
return [NSString stringWithFormat: @"\"%@\":%@", key, json];
}
+(NSString *)getNumberJson: (NSNumber *)num withKey: (NSString *)key baseClass: (Class)baseClass preKey: (NSString *)preKey {
NSString *json = nil;
if ([baseClass conformsToProtocol: @protocol(MSJsonSerializing)] && [baseClass respondsToSelector: @selector(objcValueConverter)]) {
NSDictionary *cvtDic = [baseClass objcValueConverter];
if (cvtDic != nil && [cvtDic.allKeys containsObject: preKey]) {
json = ((NSString *(^)(NSObject *obj))[cvtDic objectForKey: preKey])(num);
} else {
json = [NSString stringWithFormat: @"%@", num];
}
} else {
json = [NSString stringWithFormat: @"%@", num];;
}
if (key == nil) {
return json;
}
return [NSString stringWithFormat: @"\"%@\":%@", key, json];
}
+(NSString *)getNullJsonWithKey: (NSString *)key baseClass: (Class)baseClass preKey: (NSString *)preKey {
NSString *json = nil;
if ([baseClass conformsToProtocol: @protocol(MSJsonSerializing)] && [baseClass respondsToSelector: @selector(objcValueConverter)]) {
NSDictionary *cvtDic = [baseClass objcValueConverter];
if (cvtDic != nil && [cvtDic.allKeys containsObject: preKey]) {
json = ((NSString *(^)())[cvtDic objectForKey: preKey])();
} else {
json = @"null";
}
} else {
json = @"null";;
}
if (key == nil) {
return json;
}
return [NSString stringWithFormat: @"\"%@\":%@", key, json];
}
+(NSString *)getBoolJson: (BOOL)flag withKey: (NSString *)key baseClass: (Class)baseClass preKey: (NSString *)preKey {
return @"";
}
+(NSString *)getDateJson: (NSDate *) date withKey: (NSString *)key baseClass: (Class)baseClass preKey: (NSString *)preKey {
NSString *json = nil;
if ([baseClass conformsToProtocol: @protocol(MSJsonSerializing)] && [baseClass respondsToSelector: @selector(objcValueConverter)]) {
NSDictionary *cvtDic = [baseClass objcValueConverter];
if (cvtDic != nil && [cvtDic.allKeys containsObject: preKey]) {
json = ((NSString *(^)(NSObject *obj))[cvtDic objectForKey: preKey])(date);
} else {
json = [NSString stringWithFormat: @"%qi", (long long)([date timeIntervalSince1970]*1000)];
}
} else {
json = [NSString stringWithFormat: @"%qi", (long long)([date timeIntervalSince1970]*1000)];
}
if (key == nil) {
return json;
}
return [NSString stringWithFormat: @"\"%@\":%@", key, json];
}
+ (void)setShouldLog: (BOOL)should_log {
sShouldLog = should_log;
}
@end