使用setValue:forKey
转换应用程序对象
在我的应用程序中,我创建了一个Patient类(NSObject的子类)
患者的JSON对象如下所示
{
"id":1,
"firstName":"Angel ",
"lastName":"Merkel",
"dob":"1989-08-31",
"address":"12 th, Cross street,"
"email":"merkal@gmail.com",
"cellNumber":"213-52578522”,
”ssn":"","maritalStatus":null,
"state":null,
"regularSmoker":false
}
所以我在下面列出的 patient.h 中创建了属性,就像JSON属性名称和属性名称相同(这样我就可以使用setValueForKey
)
@property(nonatomic,assign)int idValue;// we cant declare property with name id
@property(nonatomic,strong)NSString *firstName;
@property(nonatomic,strong)NSString *lastName;
@property(nonatomic,strong)NSDate *dob;
@property(nonatomic,strong)NSString *address;
@property(nonatomic,strong)NSString *email;
@property(nonatomic,strong)NSString *cellNumber;
@property(nonatomic,strong)NSString *ssn;
@property(nonatomic,strong)NSString *maritalStatus;
@property(nonatomic,strong)NSString *state;
@property(nonatomic,strong)NSString *regularSmoker;
我使用setValuesForKeysWithDictionary:
方法将单个JSON对象转换为单个Application患者对象
转换时我必须处理以下两个问题
问题1 如果从服务器发送任何不需要的数据,请准备处理setvalueForUnIdentified密钥
-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
NSLog(@"tried to set %@ for Object %@",key,self);
[self.undefinedKeyValues setValue:value forKey:key]; // so that the unexpected key:value pairs stored
}
问题2 从JSON对象(例如
)转换为应用程序中的便捷数据类型 NSString
至NSDate
输入关键字“dob”的对象
NSNumber
到“int”类型
如下面的代码
-(void)setValue:(id)value forKey:(NSString *)key
{
if([key isEqualToString:@“id”])
{
self.idValue=[value intValue];
}
else if ([key isEqualToString:@"gender"])
{
_gender=value;
// Problem 2 handled
if([value isEqualToString:@"Male"])
{
self.genderType=MALE;
}
else if ([value isEqualToString:@"Female"])
{
self.genderType=FEMALE;
}
}
else if ([key isEqualToString:@“dob”])
{
/// convert the value to NSDate and assign
}
else
{
[super setValue:value forKey:key];
}
}
我的问题是,我可以使用上述方法将JSON对象转换为应用程序对象吗?