实例对像的数据化,刚开始开发iOS的时候,自己曾经用过,可能实际开发都用得不多,因为有KVC,或者三方框架(MJExtension)。要实现需要要运用一点点runtime的方法,但是这样比起来确实麻烦很多。
在.m文件中需要导入runtime
#import <objc/runtime.h>
实现方法:
#pragma mark --把对象转化成字典
+(NSDictionary *)getObjectData:(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];
NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
id value = [obj valueForKey:propName];
if(value== nil)
{
value = [NSNull null];
}else{
value = [self getObjectInternal:value];
}
[dic setObject:value forKey:propName];
}
return dic;
}
其中需要调用的方法:
#pragma mark --分解对象得到具体的值
+(id)getObjectInternal:(id)obj
{
if([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:[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:[objdic objectForKey:key]] forKey:key];
}
return dic;
}
return [self getObjectData:obj];
}
需要调用的方法:
#pragma mark --将对象转化成字典,并把它转化成JSON
+(NSData*)getJSON:(id)obj options:(NSJSONWritingOptions)options error:(NSError*)error{
return [NSJSONSerialization dataWithJSONObject:[self getObjectData:obj] options:options error:&error];
}