把NSObject对象输出为字典

来源:互联网 发布:ck背包 知乎 编辑:程序博客网 时间:2024/04/29 11:36

项目中需要拼接json字符串,这个调用系统方法即可:

+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;

但是这个方法里的obj对象需要是数组或字典,网上没找到相关的方法,所以我就想把数据模型对象输出为字典,字典的键就是对象的属性名,值就是属性值。

于是搞了个NSObject的类别,动态获取属性名,拼接出字典,代码如下:

#import "NSObject+PropertiesDictionary.h"//记得导入runtime,因为动态获取属性名时会用到里面的方法#import <objc/runtime.h>@implementation NSObject (PropertiesDictionary)- (NSDictionary *)propertiesDictionary{    NSMutableDictionary *dict = [NSMutableDictionary dictionary];    unsigned int outCount, i;    //获得当前类的所有属性名,属性个数存储到outCount中    objc_property_t *properties = class_copyPropertyList([self class], &outCount);    for (i = 0; i < outCount; ++i)    {        //获得属性名        objc_property_t property = properties[i];        const char *char_f = property_getName(property);        NSString *propertyName = [NSString stringWithUTF8String:char_f];        //获得属性值        id propertyValue = [self valueForKey:propertyName];        //拼接字典        if (propertyValue)        {            [dict setObject:propertyValue forKey:propertyName];        }    }    free(properties);    return dict;}@end

实测可行!
其实还可以一步到位直接输出json字符串,但是那样通用性会降低,可以再加个方法~~

对于生成json字符串,我只想到这么个方法,但是现在纠结与是直接拼个字典出来,还是建立数据模型再动态输出字典,这么做是不是太麻烦了?希望有更好方法的大神们告诉我一下,非常感谢!!!

0 0
原创粉丝点击