首页 > 移动平台 > 详细

IOS 自定义类型转换为Dictionary

时间:2015-01-23 13:04:24      阅读:435      评论:0      收藏:0      [点我收藏+]

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;
}
@end
 

IOS 自定义类型转换为Dictionary

原文:http://www.cnblogs.com/evangao/p/4243772.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!