如何将NSDictionary转换为自定义对象

我有一个JSON对象:

@interface Order : NSObject @property (nonatomic, retain) NSString *OrderId; @property (nonatomic, retain) NSString *Title; @property (nonatomic, retain) NSString *Weight; - (NSMutableDictionary *)toNSDictionary; ... - (NSMutableDictionary *)toNSDictionary { NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; [dictionary setValue:self.OrderId forKey:@"OrderId"]; [dictionary setValue:self.Title forKey:@"Title"]; [dictionary setValue:self.Weight forKey:@"Weight"]; return dictionary; } 

在string中这是:

 { "Title" : "test", "Weight" : "32", "OrderId" : "55" } 

我得到stringJSON与代码:

 NSMutableDictionary* str = [o toNSDictionary]; NSError *writeError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:NSJSONWritingPrettyPrinted error:&writeError]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 

现在我需要从JSONstring创build和映射对象

 NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *e; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e]; 

这返回填充NSDictionary。 我该怎么做才能从这本词典中得到对象呢?

添加一个新的initWithDictionary:方法来Order

 - (instancetype)initWithDictionary:(NSDictionary*)dictionary { if (self = [super init]) { self.OrderId = dictionary[@"OrderId"]; self.Title = dictionary[@"Title"]; self.Weight = dictionary[@"Weight"]; } return self; } 

不要忘记添加initWithDictionary的签名到Order.h文件

在你得到JSON的方法中:

 NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *e; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e]; Order *order = [[Order alloc] initWithDictionary:dict]; 

如果对象上的属性名称与JSONstring中的键匹配,则可以执行以下操作:

要将JSONstring映射到对象,需要先将string转换为NSDictionary,然后才能在NSObject上使用键值编码来设置每个属性。

 NSError *error = nil; NSData *jsonData = ...; // eg [myJSONString dataUsingEncoding:NSUTF8Encoding]; NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingOptionsAllowFragments error:&error]; MyObject *object = [[MyObject alloc] init]; [object setValuesForKeysWithDictionary:jsonDictionary]; 

如果键不匹配,可以覆盖对象类中NSObject的实例方法-[NSObject valueForUndefinedKey:]

要将Object映射到JSON,您可以使用Objective-C运行时自动执行此操作。 下面的代码适用于任何NSObject子类:

 #import <objc/runtime.h> - (NSDictionary *)dictionaryValue { NSMutableArray *propertyKeys = [NSMutableArray array]; Class currentClass = self.class; while ([currentClass superclass]) { // avoid printing NSObject's attributes unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList(currentClass, &outCount); for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; const char *propName = property_getName(property); if (propName) { NSString *propertyName = [NSString stringWithUTF8String:propName]; [propertyKeys addObject:propertyName]; } } free(properties); currentClass = [currentClass superclass]; } return [self dictionaryWithValuesForKeys:propertyKeys]; } 

假设你的属性名和字典键是一样的,你可以使用这个函数来转换任何对象

 - (void) setObject:(id) object ValuesFromDictionary:(NSDictionary *) dictionary { for (NSString *fieldName in dictionary) { [object setValue:[dictionary objectForKey:fieldName] forKey:fieldName]; } } 

这对你来说会更方便:

  - (instancetype)initWithDictionary:(NSDictionary*)dictionary { if (self = [super init]) { [self setValuesForKeysWithDictionary:dictionary];} return self; } 

完美的方法是通过使用库序列化/反序列化许多库可用,但我喜欢的是JagPropertyConverter https://github.com/jagill/JAGPropertyConverter

它可以将您的自定义对象转换成NSDictionary,反之亦然
即使它支持转换字典或数组或任何自定义对象内的对象(即组成)

 JAGPropertyConverter *converter = [[JAGPropertyConverter alloc]init]; converter.classesToConvert = [NSSet setWithObjects:[Order class], nil]; @interface Order : NSObject @property (nonatomic, retain) NSString *OrderId; @property (nonatomic, retain) NSString *Title; @property (nonatomic, retain) NSString *Weight; @end //For Dictionary to Object (AS IN YOUR CASE) NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; [dictionary setValue:self.OrderId forKey:@"OrderId"]; [dictionary setValue:self.Title forKey:@"Title"]; [dictionary setValue:self.Weight forKey:@"Weight"]; Order *order = [[Order alloc]init]; [converter setPropertiesOf:order fromDictionary:dictionary]; //For Object to Dictionary Order *order = [[Order alloc]init]; order.OrderId = @"10"; order.Title = @"Title; order.Weight = @"Weight"; NSDictionary *dictPerson = [converter convertToDictionary:person]; 

定义您的自定义类从“AutoBindObject”inheritance。 声明与NSDictionary中的键名称相同的属性。 然后调用方法:

 [customObject loadFromDictionary:dic]; 

实际上,我们可以自定义类来映射不同的属性名称到字典中的键。 除此之外,我们可以绑定嵌套的对象。
请看看这个演示。 用法很简单:
https://github.com/caohuuloc/AutoBindObject