iphone 把对象转成字典或json (object2dictionary)( obj2json)

来源:互联网 发布:黑马程序员怎么被辞退 编辑:程序博客网 时间:2024/05/16 07:43


当需要需要把对象装换成json,这时候就会把对象中属性值创建给dictionary,需要重复写好多的key和value;比较麻烦,耗时


写了一个NSObject类别的方法,可以直接把对象的属性值转换成字典或者json:


下载demo源码

http://download.csdn.net/detail/ydj213/8130073



关键部分代码:


#import <objc/runtime.h>
<pre name="code" class="objc">- (NSDictionary*)getDictionaryFromObject_Ext:(id)obj{    NSMutableDictionary *dic = [NSMutableDictionary dictionary];    unsigned int propsCount;    objc_property_t *props = class_copyPropertyList([obj class], &propsCount);    for(int i = 0;i < propsCount; i++) {        objc_property_t prop = props[i];        id value = nil;                @try {            NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];            value = [self getObjectInternal_Ext:[obj valueForKey:propName]];            if(value != nil) {                [dic setObject:value forKey:propName];            }        }        @catch (NSException *exception) {            //[self logError:exception];            NSLog(@"%@",exception);        }            }    free(props);    return dic;}


- (id)getObjectInternal_Ext:(id)obj{    if(!obj       || [obj isKindOfClass:[NSString class]]       || [obj isKindOfClass:[NSNumber class]]       || [obj isKindOfClass:[NSNull class]]) {        return obj;    }        if([obj isKindOfClass:[NSArray class]]) {        NSArray *objarr = obj;        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];        for(int i = 0;i < objarr.count; i++) {            [arr setObject:[self getObjectInternal_Ext:[objarr objectAtIndex:i]] atIndexedSubscript:i];        }        return arr;    }        if([obj isKindOfClass:[NSDictionary class]]) {        NSDictionary *objdic = obj;        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];        for(NSString *key in objdic.allKeys) {            [dic setObject:[self getObjectInternal_Ext:[objdic objectForKey:key]] forKey:key];        }        return dic;    }    return [self getDictionaryFromObject_Ext:obj];}

原创粉丝点击