首页 > 代码库 > IOS 自定义类型转换为Dictionary
IOS 自定义类型转换为Dictionary
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 = http://www.mamicode.com/[customClass performSelector:mySel];
if (value =http://www.mamicode.com/= nil)
{
value = http://www.mamicode.com/[NSNull null];
}
[finalDict setObject:value forKey:key];
NSLog(@"%@ %@\n", value, key);
}
[customArray addObject:finalDict];
}
return customArray;
}
@end
IOS 自定义类型转换为Dictionary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。