我正在我的iOS应用程序中的MVC API接收JSON有效载荷。然后将NSJSONSerialization
序列化为对象。该对象包含一些属性,还包含数据对象列表。数据对象是类型NSDictionary
。我已经在OBJC中具有这些对象的类结构(IM使用ODATA,所以我想将对象转换为其odataObject等效)。
所以我想知道如何将这些NSDictionary
对象施加/转换为相应的odataObject类(或真正的任何对象)?
您不能将NSDictionary
实例施放为OdataObject
,要么需要明确转换该实例,要么在应对JSON时创建适当的实例。
您可以考虑使用setValuesForKeysWithDictionary:
将字典内容推入使用KVC的另一个实例。在这种情况下,这是否有效取决于OdataObject
定义(来自GitHub?不说服)和字典内容...
编写允许转换为odataObject类的Nsdictionary的类别?对不起,我不完全理解您的要求,但是如果您需要能够将nsdictionary转换为自定义对象,那么我建议类别:
https://developer.apple.com/library/ios/documentation/cocoa/conceptual/programmingwithwithewwithewwithwithwithwithwithwithwithwithwithwithwithwithexistingclasses/customizingclasses/customizingexistingclasses.html
是的,您无法将nsdictionary实例投放到自定义模型对象。为此,您需要编写转换代码。
1)创建一个具有所需属性的nSobject的类。
2)合成所有属性
3)编写一个私人keymapping方法,该方法将您想要在模型对象中的键返回词典
-(NSDictionary *)keyMapping {
return [[NSDictionary alloc] initWithObjectsAndKeys:
@"key1", @"key1",
@"key2", @"key2",
@"key3", @"key3",
@"key4", @"key4",
@"key5", @"key5",
nil];
}
4)写入类方法,该方法将nsdictionary实例作为参数,并返回同一模型类的实例,其中填充值来自nsdictionary as(将您的字典传递给此方法)
+(ModelClass *)getModelClassObjectFromDictionary:(NSDictionary *)dictionary {
ModelClass *obj = [[ModelClass alloc] init];
NSDictionary *mapping = [obj jsonMapping];
for (NSString *attribute in [mapping allKeys]){
NSString *classProperty = [mapping objectForKey:attribute];
NSString *attributeValue = [dictionary objectForKey:attribute];
if (attributeValue!=nil&&!([attributeValue isKindOfClass:[NSNull class]])) {
[obj setValue:attributeValue forKeyPath:classProperty];
}
}
return obj;
}
就是这样。希望这对您有帮助。