IOS 自定义model如果要转换位json与服务器进行交互的时候,我把model数据类型先转换为了dictionary然后在进行json序列化。
#import <objc/runtime.h>
@implementation ConvertToCustomClass
+ (NSMutableArray *)convertCustomClassToDictionary:(NSMutableArray *)array{
NSMutableArray *customArray = [NSMutableArray array];
for (id customClass in array) {
NSString *className = NSStringFromClass([customClass class]);//获取类名
const char *cClassName = [className UTF8String];//类名编码方式
id theClass = objc_getClass(cClassName);//获取当前类类型
unsigned int outCount, i;
//获取该类的所有属性
objc_property_t *properties = class_copyPropertyList(theClass, &outCount);
NSMutableArray *propertyNames = [[NSMutableArray alloc] initWithCapacity:1];
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
//property_getName()返回属性的名字
NSString *propertyNameString = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[propertyNames addObject:propertyNameString];
//property_getAttributes()返回属性的属性
NSLog(@"%s %s\n", property_getName(property), property_getAttributes(property));
}
NSMutableDictionary *finalDict = [[NSMutableDictionary alloc] initWithCapacity:1];
for(NSString *key in propertyNames)
{
SEL mySel = NSSelectorFromString(key);
id value = [customClass performSelector:mySel];
if (value == nil)
{
value = [NSNull null];
}
[finalDict setObject:value forKey:key];
NSLog(@"%@ %@\n", value, key);
}
[customArray addObject:finalDict];
}
return customArray;