diff --git a/ARCCompile.h b/ARCCompile.h new file mode 100644 index 0000000..d2d7a09 --- /dev/null +++ b/ARCCompile.h @@ -0,0 +1,65 @@ +// +// ARCCompile.h +// CommonLibrary +// +// Created by Alexi on 14-2-10. +// Copyright (c) 2014年 CommonLibrary. All rights reserved. +// + +#ifndef CommonLibrary_ARCCompile_h +#define CommonLibrary_ARCCompile_h + +#if ! __has_feature(objc_arc) + #define CommonAutoRelease(__v) ([__v autorelease]) + #define CommonReturnAutoReleased Autorelease + + #define CommonRetain(__v) ([__v retain]) + #define CommonReturnRetained Retain + + #define CommonRelease(__v) ([__v release]) + + #define CommonDispatchQueueRelease(__v) (dispatch_release(__v)) + + #define PropertyRetain retain +// 在括号内声明时使用 + #define CommonDelegateAssign +// 在property中使用 + #define DelegateAssign assign + #define CommonSuperDealloc() [super dealloc] +#else + // -fobjc-arc + #define CommonAutoRelease(__v) + #define CommonReturnAutoReleased(__v) (__v) + + #define CommonRetain(__v) + #define CommonReturnRetained(__v) (__v) + + #define CommonRelease(__v) + + #define PropertyRetain strong + #define CommonDelegateAssign __unsafe_unretained + #define DelegateAssign unsafe_unretained + #define CommonSuperDealloc() + + #if TARGET_OS_IPHONE + // Compiling for iOS + #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000 + // iOS 6.0 or later + #define CommonDispatchQueueRelease(__v) + #else + // iOS 5.X or earlier + #define CommonDispatchQueueRelease(__v) (dispatch_release(__v)) + #endif + #else + // Compiling for Mac OS X + #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 + // Mac OS X 10.8 or later + #define CommonDispatchQueueRelease(__v) + #else + // Mac OS X 10.7 or earlier + #define CommonDispatchQueueRelease(__v) (dispatch_release(__v)) + #endif + #endif +#endif + +#endif diff --git a/DebugMarco.h b/DebugMarco.h new file mode 100644 index 0000000..0e4534b --- /dev/null +++ b/DebugMarco.h @@ -0,0 +1,42 @@ +// +// DebugMarco.h +// CommonLibrary +// +// Created by Alexi on 13-10-23. +// Copyright (c) 2013年 ywchen. All rights reserved. +// + +#ifndef CommonLibrary_DebugMarco_h +#define CommonLibrary_DebugMarco_h + +// 日志 + +#ifdef DEBUG + +#ifndef DebugLog +#define DebugLog(fmt, ...) NSLog((@"[%s Line %d] \n" fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) + +#define NSLog(fmt, ...) fprintf(stderr,"%s [%s %d]\n%s\n\n",[[NSDate date].description UTF8String],[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:fmt, ##__VA_ARGS__] UTF8String]); + + + +#define DBErrorLog(fmt, ...) fprintf(stderr,"%s DBErrorLog_[%s %d]\n\n%s\n\n\n",[[NSDate date].description UTF8String],[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:fmt, ##__VA_ARGS__] UTF8String]); + + +#endif + +#else + +#define DebugLog(fmt, ...) // NSLog((@"[%s Line %d] \n" fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) + +#define CallDebugLog(fmt, ...) fprintf(stderr,"%s CallDebugLog_[%s %d]\n%s\n\n", [[NSDate date].description UTF8String], [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:fmt, ##__VA_ARGS__] UTF8String]); + +#define DBErrorLog(fmt, ...) fprintf(stderr,"%s DBErrorLog_[%s %d]\n\n%s\n\n\n",[[NSDate date].description UTF8String],[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:fmt, ##__VA_ARGS__] UTF8String]); + +#define NSLog(...) // NSLog + + +#endif + +#endif + diff --git a/NSDictionary+JSON.h b/NSDictionary+JSON.h new file mode 100644 index 0000000..fd912b4 --- /dev/null +++ b/NSDictionary+JSON.h @@ -0,0 +1,34 @@ +// +// NSDictionary+JSON.h +// XJD +// +// Created by xyx on 2017/6/17. +// Copyright © 2017年 Shenzhen Xiyou Co., Ltd.. All rights reserved. +// + +#import + +@interface NSDictionary (JSON) + + +//将NSDictionary中的Null类型的项目转化成@"" ++(NSDictionary *)nullDic:(NSDictionary *)myDic; + + +//将NSDictionary中的Null类型的项目转化成@"" ++(NSArray *)nullArr:(NSArray *)myArr; + + +//将NSString类型的原路返回 ++(NSString *)stringToString:(NSString *)string; + + +//将Null类型的项目转化成@"" ++(NSString *)nullToString; + + +#pragma mark - 公有方法 +//类型识别:将所有的NSNull类型转化成@"" ++(id)changeType:(id)myObj; + +@end diff --git a/NSDictionary+JSON.m b/NSDictionary+JSON.m new file mode 100644 index 0000000..350f494 --- /dev/null +++ b/NSDictionary+JSON.m @@ -0,0 +1,83 @@ +// +// NSDictionary+JSON.m +// XJD +// +// Created by xyx on 2017/6/17. +// Copyright © 2017年 Shenzhen Xiyou Co., Ltd.. All rights reserved. +// + +#import "NSDictionary+JSON.h" + +@implementation NSDictionary (JSON) + +//将NSDictionary中的Null类型的项目转化成@"" ++(NSDictionary *)nullDic:(NSDictionary *)myDic +{ + NSArray *keyArr = [myDic allKeys]; + NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init]; + for (int i = 0; i < keyArr.count; i ++) + { + id obj = [myDic objectForKey:keyArr[i]]; + + obj = [self changeType:obj]; + + [resDic setObject:obj forKey:keyArr[i]]; + } + return resDic; +} + +//将NSDictionary中的Null类型的项目转化成@"" ++(NSArray *)nullArr:(NSArray *)myArr +{ + NSMutableArray *resArr = [[NSMutableArray alloc] init]; + for (int i = 0; i < myArr.count; i ++) + { + id obj = myArr[i]; + + obj = [self changeType:obj]; + + [resArr addObject:obj]; + } + return resArr; +} + +//将NSString类型的原路返回 ++(NSString *)stringToString:(NSString *)string +{ + return string; +} + +//将Null类型的项目转化成@"" ++(NSString *)nullToString +{ + return @""; +} + +#pragma mark - 公有方法 +//类型识别:将所有的NSNull类型转化成@"" ++(id)changeType:(id)myObj +{ + if ([myObj isKindOfClass:[NSDictionary class]]) + { + return [self nullDic:myObj]; + } + else if([myObj isKindOfClass:[NSArray class]]) + { + return [self nullArr:myObj]; + } + else if([myObj isKindOfClass:[NSString class]]) + { + return [self stringToString:myObj]; + } + else if([myObj isKindOfClass:[NSNull class]]) + { + return [self nullToString]; + } + else + { + return myObj; + } +} + + +@end diff --git a/NSDictionary+JSONString.h b/NSDictionary+JSONString.h new file mode 100644 index 0000000..901136e --- /dev/null +++ b/NSDictionary+JSONString.h @@ -0,0 +1,13 @@ +// +// NSDictionary+JSONString.h +// WHua +// +// Created by XYX on 3/11/14. +// Copyright (c) 2014 User. All rights reserved. +// + +#import + +@interface NSDictionary (JSONString) +-(NSString*)NSDictionary2jsonString; +@end diff --git a/NSDictionary+JSONString.m b/NSDictionary+JSONString.m new file mode 100644 index 0000000..75a5a21 --- /dev/null +++ b/NSDictionary+JSONString.m @@ -0,0 +1,27 @@ +// +// NSDictionary+JSONString.m +// WHua +// +// Created by XYX on 3/11/14. +// Copyright (c) 2014 User. All rights reserved. +// + +#import "NSDictionary+JSONString.h" + +@implementation NSDictionary (JSONString) + +-(NSString*)NSDictionary2jsonString +{ + NSString *jsonString = nil; + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self + options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string + error:&error]; + if (! jsonData) { + + } else { + jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + } + return jsonString; +} +@end diff --git a/NSMutableDictionary+Json.h b/NSMutableDictionary+Json.h new file mode 100644 index 0000000..6dfb747 --- /dev/null +++ b/NSMutableDictionary+Json.h @@ -0,0 +1,47 @@ +// +// NSMutableDictionary+Json.h +// CommonLibrary +// +// Created by Alexi on 14-1-16. +// Copyright (c) 2014年 CommonLibrary. All rights reserved. +// + +#import + +@interface NSMutableDictionary (Json) + +- (void)addString:(NSString *)aValue forKey:(id)aKey; + +- (void)addInteger:(NSInteger)aValue forKey:(id)aKey; + +- (void)addCGFloat:(CGFloat)aValue forKey:(id)aKey; + +- (void)addBOOL:(BOOL)aValue forKey:(id)aKey; + +- (void)addBOOLStr:(BOOL)aValue forKey:(id)aKey; + +- (void)addNumber:(NSNumber *)aValue forKey:(id)aKey; + +- (void)addArray:(NSArray *)aValue forKey:(id)aKey; + +- (NSString *)convertToJSONString; + +//- (id)jsonObjectForKey:(id)key; + +@end + +@interface NSDictionary (Json) + +//- (id)jsonObjectForKey:(id)key; + +- (NSMutableDictionary *)dictionaryForKey:(id)key; +- (NSString *)stringForKey:(id)key; +- (NSInteger)integerForKey:(id)key; +- (BOOL)boolForKey:(id)key; +- (CGFloat)floatForKey:(id)key; +- (double)doubleForKey:(id)key; +- (NSMutableArray *)arrayForKey:(id)key; + +@end + + diff --git a/NSMutableDictionary+Json.m b/NSMutableDictionary+Json.m new file mode 100644 index 0000000..5a40861 --- /dev/null +++ b/NSMutableDictionary+Json.m @@ -0,0 +1,161 @@ +// +// NSMutableDictionary+Json.m +// CommonLibrary +// +// Created by Alexi on 14-1-16. +// Copyright (c) 2014年 CommonLibrary. All rights reserved. +// + +#import "NSMutableDictionary+Json.h" + +@implementation NSMutableDictionary (Json) + +- (void)addString:(NSString *)aValue forKey:(id )aKey +{ + if (aValue == nil) + { + [self setObject:@"" forKey:aKey]; + } + else + { + [self setObject:aValue forKey:aKey]; + } +} + +- (void)addInteger:(NSInteger)aValue forKey:(id )aKey +{ + [self addNumber:[NSNumber numberWithInteger:aValue] forKey:aKey]; +} + + +- (void)addCGFloat:(CGFloat)aValue forKey:(id )aKey +{ + [self addNumber:[NSNumber numberWithDouble:aValue] forKey:aKey]; +} + + +- (void)addBOOL:(BOOL)aValue forKey:(id )aKey +{ +// [self addString:aValue ? @"Y" : @"N" forKey:aKey]; + [self addNumber:[NSNumber numberWithBool:aValue] forKey:aKey]; +} + +- (void)addBOOLStr:(BOOL)aValue forKey:(id )aKey +{ + [self addString:aValue ? @"Y" : @"N" forKey:aKey]; +} + + +- (void)addNumber:(NSNumber *)aValue forKey:(id )aKey +{ + [self setObject:aValue forKey:aKey]; +} + +- (void)addArray:(NSArray *)aValue forKey:(id )aKey +{ + if (aValue == nil) { + [self setObject:[NSNull null] forKey:aKey]; + } + else + { + [self setObject:aValue forKey:aKey]; + } +} + + +- (NSString *)convertToJSONString +{ + if ([NSJSONSerialization isValidJSONObject:self]) + { + NSError *error = nil; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error: &error]; + NSString *string = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return string; + } + return nil; +} + + + + +@end + +@implementation NSDictionary (Json) + +- (id)jsonObjectForKey:(id)key +{ + id value = [self objectForKey:key]; + if ([value isKindOfClass:[NSNull class]]) { + return nil; + } + return value; +} +- (NSMutableDictionary *)dictionaryForKey:(id)key +{ + NSDictionary *dic = (NSDictionary *)[self jsonObjectForKey:key]; + return [NSMutableDictionary dictionaryWithDictionary:dic]; +} + +- (NSString *)stringForKey:(id)key +{ + return [self jsonObjectForKey:key]; +} + +- (NSNumber *)numberForKey:(id)key +{ + NSNumber *num = [self jsonObjectForKey:key]; + return num; +} + +- (NSInteger)integerForKey:(id)key +{ + return [self numberForKey:key].integerValue; +} + +- (BOOL)boolForKey:(id)key +{ + id va = [self jsonObjectForKey:key]; + if (va) + { + if ([va isKindOfClass:[NSString class]]) + { + NSString *value = (NSString *)va; + return [[value lowercaseString] isEqualToString:@"y"]; + + } + else + { + return [self numberForKey:key].boolValue; + } + } + + return NO; + + +} + +- (CGFloat)floatForKey:(id)key +{ + return [self numberForKey:key].floatValue; +} + +- (double)doubleForKey:(id)key +{ + return [self numberForKey:key].doubleValue; +} + +- (NSMutableArray *)arrayForKey:(id)key +{ + NSArray *array = [self jsonObjectForKey:key]; + + NSMutableArray *mutablearray = [NSMutableArray array]; + + for (NSDictionary *dic in array) { + NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:dic]; + [mutablearray addObject:mdic]; + } + + return mutablearray; +} + +@end diff --git a/NSNull+InternalNullExtention.h b/NSNull+InternalNullExtention.h new file mode 100644 index 0000000..fac5d96 --- /dev/null +++ b/NSNull+InternalNullExtention.h @@ -0,0 +1,16 @@ +// +// NSNull+InternalNullExtention.h +// BabyCare +// +// Created by xyx on 15/4/8. +// Copyright (c) 2015年 Qiwo SmartLink Technology Ltd. All rights reserved. +// + +#import + + +#define NSNullObjects @[@"",@0,@{},@[]] + +@interface NSNull (InternalNullExtention) + +@end diff --git a/NSNull+InternalNullExtention.m b/NSNull+InternalNullExtention.m new file mode 100644 index 0000000..29b3405 --- /dev/null +++ b/NSNull+InternalNullExtention.m @@ -0,0 +1,45 @@ +// +// NSNull+InternalNullExtention.m +// BabyCare +// +// Created by xyx on 15/4/8. +// Copyright (c) 2015年 Qiwo SmartLink Technology Ltd. All rights reserved. +// + +#import "NSNull+InternalNullExtention.h" + + + +@implementation NSNull (InternalNullExtention) + + +- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector +{ + NSMethodSignature* signature = [super methodSignatureForSelector:selector]; + if (!signature) { + for (NSObject *object in NSNullObjects) { + signature = [object methodSignatureForSelector:selector]; + if (signature) { + break; + } + } + } + return signature; +} + + +- (void)forwardInvocation:(NSInvocation *)anInvocation +{ + SEL aSelector = [anInvocation selector]; + for (NSObject *object in NSNullObjects) { + if ([object respondsToSelector:aSelector]) { + [anInvocation invokeWithTarget:object]; + return; + } + } + [self doesNotRecognizeSelector:aSelector]; +} + + + +@end diff --git a/NSObject+Json.h b/NSObject+Json.h new file mode 100644 index 0000000..b8e6519 --- /dev/null +++ b/NSObject+Json.h @@ -0,0 +1,110 @@ +// +// NSObject+Json.h +// Json反序列化代码 +// +// Created by Alexi on 12-11-15. +// Copyright (c) 2012年. All rights reserved. +// + +#import + +/* + * 说明: + * 使用该代码的前提: 因需要通过json中返回的key值,查找相应的数据类型,然后再进行赋 + * 所以在客户端在拿到服务端返回的json字符串后,客户端进行数据Modal定义时,Modal的属性名与json中的一致。 + * 举例如下: + * 服务端返回的一个User对像的json串 + * {"name":"Alexi","age":26} + * 那么本地定义如下: + * @interface User : NSObject + * { + * NSString *_name; + * NSInteger _age; + * } + * + * @property (nonatomic, copy) NSString *name; + * @property (nonatomic, assign) NSInteger age; + * + * @end + */ + + + +@interface NSObject (Json) + + +// 因Server端经常使用id作表字段,而objc中id是关键字,不能作为属性 +// 所以解析前,先检查有不有id字段 +// 如果有,则对属性进行赋值 +// 具体由子类进行重写 +- (void)setIdPropertyValue:(id)idkeyValue; + +// 设置复杂对象 +- (void)setValueForPropertyValue:(id)idkeyValue forKey:(NSString *)key propertyClass:(Class)cls tagretClass:(Class)targetCls; + +// 将json数据反序列化成一个对象 +// Json格式如下: +/* + {"name":"Alexi","age":26,"studentId":"06061096","QQ":"403725592"} + */ ++ (id)parse:(Class)aClass jsonString:(NSString *)json; ++ (id)parse:(Class)aClass dictionary:(NSDictionary *)dict; + + +// 对于格式如下的方法,使用以下接口进行反序化 +/* + * [{itemClass对应的json串},{itemClass对应的json串}...] + */ + ++ (NSMutableArray *)loadItem:(Class)itemClass fromDictionary:(NSArray *)arraydict; ++ (NSMutableArray *)loadItem:(Class)itemClass fromJsonString:(NSString *)json; ++ (NSMutableArray *)loadItem:(Class)itemClass fromArrayDictionary:(NSArray *)arraydict; + + +// 将json数据反序列化成一个对象 +// 缺点 : 不能解格嵌套的数组 +// Json格式如下: +/* + {"name":"Alexi","age":26,"studentId":"06061096","QQ":"403725592",bookItems:[{bookItemClass对应的json串},{bookItemClass对应的json串}...]} + */ ++ (id)parse:(Class)aClass dictionary:(NSDictionary *)dict itemClass:(Class)itemClass; ++ (id)parse:(Class)aClass jsonString:(NSString *)json itemClass:(Class)itemClass; + +// 目前代码中存在以下问题,后期再进行更新 +// 对于Json格式如下的数据不能直接反序列化成对象: +/* + {"name":"Alexi","age":26,"studentId":"06061096","QQ":"403725592",bookItems:[{bookItemClass对应的json串},{bookItemClass对应的json串}...],friends:[{friendClass对应的json串},{friendClass对应的json串}...]} + + * 可先调用 + * [NSObject parse:[User class] dictionary:dict]; 将一些普通的属性进行设置 + * 然后再获取到 + * bookItems对应的Json列表: NSArray *bookItemJsonArray = [dict objectForKey:@"bookItems"]; + * self.bookItems = [self loadItem:[BookItem class] fromDictionary:bookItemJsonArray]; + * 同理可对friends进行设置 + */ + + +- (void)propertyListOfClass:(Class)aclass propertyList:(NSMutableDictionary *)propertyDic; +// 把对象的属性(会将其至基类NSObject的所有属性)序列化成Json字典, 以属性名作为键值 +- (id)serializeToJsonObject; + +// 把对象自身的属性序列化成Json字典, 以属性名作为键值 +- (id)serializeSelfPropertyToJsonObject; + ++ (id)loadInfo:(Class)aclass withKey:(NSString *)key; + ++ (void)saveInfo:(NSObject *)obj withKey:(NSString *)key; +@end + + +@interface NSArray (serializeToJsonObject) + +- (id)serializeToJsonObject; + +@end + +@interface NSDictionary (serializeToJsonObject) + +- (id)serializeToJsonObject; + +@end diff --git a/NSObject+Json.m b/NSObject+Json.m new file mode 100644 index 0000000..49910a8 --- /dev/null +++ b/NSObject+Json.m @@ -0,0 +1,613 @@ +// +// NSObject+Json.m +// +// +// Created by Alexi on 12-11-15. +// Copyright (c) 2012年 . All rights reserved. +// + +#import "NSObject+Json.h" +#import + +#import "JSONKit.h" + +#import "IOSDeviceConfig.h" + +@implementation NSObject (Json) + +#define kServiceTag_ID @"id" + +- (void)setIdPropertyValue:(id)idkeyValue +{ + // for the subclass to do +} + +/* + * 对于格式如下的方法,使用以下接口进行反序化 + * [{itemClass对应的json串},{itemClass对应的json串}...] + * 参数说明: + * itemClass: json列表中单个数据对要反序列化成的对像类型 + * arraydict: json列表 + */ ++ (NSMutableArray *)loadItem:(Class)itemClass fromArrayDictionary:(NSArray *)arraydict +{ + NSMutableArray *array = [[NSMutableArray alloc] init]; + + for (NSDictionary *dic in arraydict ) { + if (dic) { + id value = [NSObject parse:itemClass dictionary:dic]; + [array addObject:value]; + } + } + return CommonReturnAutoReleased(array); +} + +/* + * + */ + +- (void)setValueForPropertyValue:(id)idkeyValue forKey:(NSString *)key propertyClass:(Class)cls tagretClass:(Class)targetCls +{ + if ([idkeyValue isKindOfClass:[NSDictionary class]]) + { + // 说明要赋值的属性是NSObject的子类 + id value = [NSObject parse:targetCls dictionary:idkeyValue itemClass:cls]; + [self setValue:value forKey:key]; + } + else if ([idkeyValue isKindOfClass:[NSArray class]]) + { + // NSMutableArray *array = [[NSMutableArray alloc] init]; + // for (NSDictionary *dic in idkeyValue ) { + // if (dic) { + // id value = [NSObject parse:cls dictionary:dic]; + // [array addObject:value]; + // } + // } + // + // [self setValue:array forKey:key]; + // [array release]; + // 说明要赋值的属性是一个列表 + NSMutableArray *arrayValue = (NSMutableArray *)[NSObject loadItem:cls fromArrayDictionary:idkeyValue]; + + [self setValue:arrayValue forKey:key]; + } +} + +// 遍历 + +- (void)enumerateProperty:(NSString *)propertyName value:(id)idvalue propertyDictionary:(NSDictionary *)propertyKeys +{ + if ([idvalue isKindOfClass:[NSNull class]]) + { + NSString *proClsName = [propertyKeys objectForKey:propertyName]; + if ([proClsName hasPrefix:@"T@"]) + { + [self setValue:nil forKey:propertyName]; + } + else + { + NSNumber *num = [NSNumber numberWithInteger:0]; + [self setValue:num forKey:propertyName]; + } + } + else + { + if (idvalue) + { + NSString *proClsName = [propertyKeys objectForKey:propertyName]; + + if ([proClsName hasPrefix:@"T@"]) + { + NSRange range = [proClsName rangeOfString:@"\""]; + NSString *test = [proClsName substringFromIndex:range.location+1]; + range = [test rangeOfString:@"\""]; + NSString *realClassName = [test substringToIndex:range.location]; + Class proCls = NSClassFromString(realClassName); + + if ([idvalue isKindOfClass:proCls] && ![idvalue isKindOfClass:[NSMutableArray class]] && ![idvalue isKindOfClass:[NSMutableDictionary class]]) + { + [self setValue:idvalue forKey:propertyName]; + } + else + { + [self setValueForPropertyValue:idvalue forKey:propertyName propertyClass:proCls tagretClass:proCls]; + } + } + else + { + if ([idvalue isKindOfClass:[NSDecimalNumber class]]) { + NSDecimalNumber *num = (NSDecimalNumber *)idvalue; + [self setValue:num forKey:propertyName]; + } + else + { + NSNumber *num = (NSNumber *)idvalue; + [self setValue:num forKey:propertyName]; + + } + } + } + + } + +} + ++ (id)parse:(Class)aClass dictionary:(NSDictionary *)dict +{ + + id aClassInstance = [[aClass alloc] init]; + CommonAutoRelease(aClassInstance); + + // 因JSON返回的字段中有id + // 所以对此数据作特处理 + id idTagValue = [dict objectForKey:kServiceTag_ID]; + if (idTagValue) { + [aClassInstance setIdPropertyValue:idTagValue]; + } + + // 将返回的Json键与aClassInstance的属性列表进行一次对比,找出要赋值的属性,以减少不必要的运算 + NSDictionary *propertyKeys = [aClassInstance enumerateKeysInDictionary:dict]; + CommonRetain(propertyKeys); + + NSArray *propertyKeysArray = [propertyKeys allKeys]; + + // 逐一对相关的属性进行设置 + for (unsigned int i = 0 ; i < propertyKeysArray.count; i++ ) + { + NSString *propertyName = [propertyKeysArray objectAtIndex:i]; + id idvalue = [dict objectForKey:propertyName]; + + // propertyName:要设置的属性名 + // idvalue:对应的值 + [aClassInstance enumerateProperty:propertyName value:idvalue propertyDictionary:propertyKeys]; + } + + CommonRelease(propertyKeys); + return aClassInstance; +} + +- (NSMutableDictionary *)propertyListOfClass:(Class)class +{ + NSMutableDictionary *dic = [NSMutableDictionary dictionary]; + + unsigned int propertyCount = 0; + objc_property_t *propertyList = class_copyPropertyList(class, &propertyCount); + for (unsigned int i = 0 ; i < propertyCount; i++ ) + { + const char *pcName = property_getName(propertyList[i]); + NSString *propertyName = [NSString stringWithCString:pcName encoding:NSUTF8StringEncoding]; + + const char *proClsNameCStr = property_getAttributes(propertyList[i]); + NSString *proClsName = [NSString stringWithCString:proClsNameCStr encoding:NSUTF8StringEncoding]; + [dic setObject:proClsName forKey:propertyName]; + + } + free(propertyList); + + if (class != [NSObject class]) + { + // 去掉NSObject里面的属性 + NSMutableDictionary *ObjectClass = [self propertyListOfClass:[NSObject class]]; + + [dic removeObjectsForKeys:[ObjectClass allKeys]]; + + // iOS8以前dic会加上这几个不用的键值 @[@"debugDescription", @"description", @"hash", @"superclass"] + if (![IOSDeviceConfig sharedConfig].isIOS7Later) + { + [dic removeObjectsForKeys:@[@"debugDescription", @"description", @"hash", @"superclass"]]; + } +// { +// debugDescription = "T@\"NSString\",R,C"; +// description = "T@\"NSString\",R,C"; +// hash = "TQ,R"; +// pageIndex = "Tq,N,V_pageIndex"; +// pageSize = "Tq,N,V_pageSize"; +// superclass = "T#,R"; +// } + } + + + + + return dic; +} + +// 返回class的所有属性列表(包括当前类至NSObject类的之间所有继承关系对象的列表) +- (void)propertyListOfClass:(Class)class propertyList:(NSMutableDictionary *)propertyDic +{ + if (class == [NSObject class]) + { + return; + } + else + { + // 添加class属性列表到返回结果里面 + NSDictionary *selfDic = [self propertyListOfClass:class]; + [propertyDic addEntriesFromDictionary:selfDic]; + + // 继续查找class的父类 + Class superClass = class_getSuperclass(class); + [self propertyListOfClass:superClass propertyList:propertyDic]; + } + +} + + +// 通过返回的Json字典valueDict的keys,过滤出需要设置的属性名名称及对应的类型 +// 返回:过滤后需要设置的() + +- (NSDictionary *)enumerateKeysInDictionary:(NSDictionary *)valueDict +{ + NSUInteger propertyCount = 0; + + NSMutableDictionary *propertyKeys = [[NSMutableDictionary alloc] init]; + CommonAutoRelease(propertyKeys); + + NSMutableDictionary *dic = [NSMutableDictionary dictionary]; + [self propertyListOfClass:[self class] propertyList:dic]; + + NSArray *dicKeys = [dic allKeys]; + propertyCount = dicKeys.count; + + NSArray *valueDictKeys = [valueDict allKeys]; + + for (int i = 0; i < propertyCount; i++) { + NSString *propertyName = [dicKeys objectAtIndex:i]; + + if ([valueDictKeys containsObject:propertyName]) + { + [propertyKeys setObject:[dic valueForKey:propertyName] forKey:propertyName]; + } + } + + return propertyKeys; +} + + +- (void)enumerateProperty:(NSString *)propertyName value:(id)idvalue propertyDictionary:(NSDictionary *)propertyKeys itemClass:(Class)itemClass +{ + if ([idvalue isKindOfClass:[NSNull class]]) + { + [self setValue:nil forKey:propertyName]; + } + else + { + if (idvalue) + { + NSString *proClsName = [propertyKeys objectForKey:propertyName]; + + if ([proClsName hasPrefix:@"T@"]) + { + NSRange range = [proClsName rangeOfString:@"\""]; + NSString *test = [proClsName substringFromIndex:range.location+1]; + range = [test rangeOfString:@"\""]; + NSString *realClassName = [test substringToIndex:range.location]; + Class proCls = NSClassFromString(realClassName); + + if ([idvalue isKindOfClass:proCls] && ![idvalue isKindOfClass:[NSMutableArray class]] && ![idvalue isKindOfClass:[NSMutableDictionary class]]) + { + [self setValue:idvalue forKey:propertyName]; + } + else + { + [self setValueForPropertyValue:idvalue forKey:propertyName propertyClass:itemClass tagretClass:proCls]; + } + } + else + { + if ([idvalue isKindOfClass:[NSDecimalNumber class]]) { + NSDecimalNumber *num = (NSDecimalNumber *)idvalue; + [self setValue:num forKey:propertyName]; + } + else + { + NSNumber *num = (NSNumber *)idvalue; + [self setValue:num forKey:propertyName]; + + } + + } + } + + } + +} + + ++ (id)parse:(Class)aClass dictionary:(NSDictionary *)dict itemClass:(Class)itemClass +{ + id aClassInstance = [[aClass alloc] init]; + CommonAutoRelease(aClassInstance); + + // 因JSON返回的字段中有id + // 所以对此数据作特处理 + id idTagValue = [dict objectForKey:kServiceTag_ID]; + if (idTagValue) { + [aClassInstance setIdPropertyValue:idTagValue]; + } + + NSDictionary *propertyKeys = [aClassInstance enumerateKeysInDictionary:dict]; + CommonRetain(propertyKeys); + + NSArray *propertyKeysArray = [propertyKeys allKeys]; + for (unsigned int i = 0 ; i < propertyKeysArray.count; i++ ) + { + NSString *propertyName = [propertyKeysArray objectAtIndex:i]; + id idvalue = [dict objectForKey:propertyName]; + [aClassInstance enumerateProperty:propertyName value:idvalue propertyDictionary:propertyKeys itemClass:itemClass]; + + } + CommonRelease(propertyKeys); + // [propertyKeys release]; + + return aClassInstance; + +} + + ++ (id)parse:(Class)aClass jsonString:(NSString *)json +{ + NSDictionary *dic = [json objectFromJSONString]; + return dic ? [NSObject parse:aClass dictionary:dic] : nil; +} + ++ (id)parse:(Class)aClass jsonString:(NSString *)json itemClass:(Class)itemClass +{ + NSDictionary *dic = [json objectFromJSONString]; + return dic ? [NSObject parse:aClass dictionary:dic itemClass:itemClass] : nil; +} + ++ (NSMutableArray *)loadItem:(Class)itemClass fromDictionary:(NSArray *)arraydict +{ + NSMutableArray *array = [[NSMutableArray alloc] init]; + + for (NSDictionary *dic in arraydict ) { + if (dic) { + // 遍历数据中单个字典元素,将期反序列化成itemClass对象实例 + id value = [NSObject parse:itemClass dictionary:dic]; + [array addObject:value]; + } + } + return CommonReturnAutoReleased(array); +} ++ (NSMutableArray *)loadItem:(Class)itemClass fromJsonString:(NSString *)json +{ + NSArray *dic = [json objectFromJSONString]; + return dic ? [NSObject loadItem:itemClass fromJsonString:json] : nil; +} + +- (id)serializeToJsonObject +{ + if ([NSJSONSerialization isValidJSONObject:self]) + { + return self; + } + + if ([self isMemberOfClass:[NSObject class]]) + { + // 解析到此 + return nil; + } + + NSMutableDictionary *jsonDic = [NSMutableDictionary dictionary]; + + // 将返回的Json键与aClassInstance的属性列表进行一次对比,找出要赋值的属性,以减少不必要的运算 + NSMutableDictionary *propertyKeys = [NSMutableDictionary dictionary]; + + [self propertyListOfClass:[self class] propertyList:propertyKeys]; + + NSArray *propertyKeysArray = [propertyKeys allKeys]; + + // 逐一对相关的属性进行设置 + for (unsigned int i = 0 ; i < propertyKeysArray.count; i++ ) + { + NSString *propertyName = [propertyKeysArray objectAtIndex:i]; + + NSString *propertType = [propertyKeys valueForKey:propertyName]; + + if ([propertType hasPrefix:@"T@"]) + { + // 对应类 + id idvalue = [self valueForKey:propertyName]; + if (idvalue) + { + if ([idvalue isKindOfClass:[NSString class]]) + { + [jsonDic setObject:idvalue forKey:propertyName]; + } + else + { + id idvalueJson = [idvalue serializeToJsonObject]; + if (idvalueJson) + { + [jsonDic setObject:idvalueJson forKey:propertyName]; + } + } + } + + } + else + { + // 基本数据类型 + id idvalue = [self valueForKey:propertyName]; + [jsonDic setObject:idvalue forKey:propertyName]; + } + + } + + return jsonDic; +} + + +// 把对象自身的属性序列化成Json字典, 以属性名作为键值 +- (id)serializeSelfPropertyToJsonObject +{ + if ([NSJSONSerialization isValidJSONObject:self]) + { + return self; + } + + if ([self isMemberOfClass:[NSObject class]]) + { + // 解析到此 + return nil; + } + + NSMutableDictionary *jsonDic = [NSMutableDictionary dictionary]; + + // 将返回的Json键与aClassInstance的属性列表进行一次对比,找出要赋值的属性,以减少不必要的运算 + NSMutableDictionary *propertyKeys = [self propertyListOfClass:[self class]]; + + NSArray *propertyKeysArray = [propertyKeys allKeys]; + + // 逐一对相关的属性进行设置 + for (unsigned int i = 0 ; i < propertyKeysArray.count; i++ ) + { + NSString *propertyName = [propertyKeysArray objectAtIndex:i]; + + NSString *propertType = [propertyKeys valueForKey:propertyName]; + + if ([propertType hasPrefix:@"T@"]) + { + // 对应类 + id idvalue = [self valueForKey:propertyName]; + if (idvalue) + { + if ([idvalue isKindOfClass:[NSString class]]) + { + NSString *stringValue = (NSString *)idvalue; + if (stringValue.length) + { + [jsonDic setObject:idvalue forKey:propertyName]; + } + else + { + [jsonDic setObject:@"" forKey:propertyName]; + } + } + else + { + id idvalueJson = [idvalue serializeToJsonObject]; + if (idvalueJson) + { + [jsonDic setObject:idvalueJson forKey:propertyName]; + } + } + } + + } + else + { + // 基本数据类型 + id idvalue = [self valueForKey:propertyName]; + [jsonDic setObject:idvalue forKey:propertyName]; + } + + } + + return jsonDic; +} + ++ (id)loadInfo:(Class)aclass withKey:(NSString *)key +{ + NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; + NSString *loginInfo = [ud objectForKey:key]; + if (loginInfo) + { + id ret = [NSObject parse:[aclass class] jsonString:loginInfo]; + if (ret) + { + return ret; + } + else + { + return loginInfo; + } + } + return nil; +} + + ++ (void)saveInfo:(NSObject *)obj withKey:(NSString *)key +{ + NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; + if (obj) + { + if ([obj isKindOfClass:[NSString class]]) + { + [ud setObject:obj forKey:key]; + } + else + { + NSDictionary *dic = [obj serializeToJsonObject]; + + if ([NSJSONSerialization isValidJSONObject:dic]) + { + NSError *error = nil; + NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error]; + if(error) + { + DebugLog(@"存储失败"); + } + NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + [ud setObject:str forKey:key]; + } + } + + [ud synchronize]; + } + else + { + [ud removeObjectForKey:key]; + } +} + + +@end + + +@implementation NSArray (serializeToJsonObject) + +- (id)serializeToJsonObject +{ + if ([NSJSONSerialization isValidJSONObject:self]) + { + return self; + } + + NSMutableArray *array = [NSMutableArray array]; + for (id obj in self) + { + id jsonObj = [obj serializeToJsonObject]; + if (jsonObj) + { + [array addObject:jsonObj]; + } + } + + if (array.count) + { + if ([NSJSONSerialization isValidJSONObject:array]) + { + return array; + } + } + + DebugLog(@"[%@] can't convert to vaild Json", self); + return nil; +} + +@end + +@implementation NSDictionary (serializeToJsonObject) + +- (id)serializeToJsonObject +{ + if ([NSJSONSerialization isValidJSONObject:self]) + { + return self; + } + return nil; +} + +@end \ No newline at end of file