project link: https://github.com/CoderMJLee/MJExtension
There are two major factors when we want to parse backend response. 1. the meaningful keys; 2. the data structure of correspond these keys. So, how to use MJExtension to solve your problems? Let me demostrate you.
1.the meaningful keys
The definition of specific name:
model: subclass of NSObject or NSManagedObject class, to describe and parse the data from backend, that you want to transfter them in UI or save them into database.
a. JSON dictionary to model
b. JSON array to model array
c. rename
d. the same property of model from different keys in backend
2.the data structure of correspond these keys
If app wants to keep the same data structure as backend reponse, it isnot a big deal. In this case, app maybe just want to rename it. Such as, receiving the key 'id', app can rename it to 'collectionID' or any others. However, app wants to modify the datastructure of one key, how to solve the problem. For example: the key 'company_ids' is the number value type, app wants to change it to array of number. As following:
- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property
{
if ([property.name isEqualToString:@"company_ids"] && ![oldValue respondsToSelector:@selector(count)] ) {
if (oldValue == nil) {
return oldValue;
} else if ([oldValue isKindOfClass:[NSString class]]) {
return [NSArray arrayWithObject:@(((NSString *)oldValue).integerValue)];
} else if ([oldValue isKindOfClass:[NSNumber class]]) {
return [NSArray arrayWithObject:oldValue];
}
}
return oldValue;
}
问题:
property.type.typeClass中打印出来的数据类型,并不是服务器端返回数据的真正类型似乎为定义model对象时,所设定的数据类型。例如,company_ids在定义model时,将其设定为array类型的,因此打印出来的都为array。因此,我在做判断时使用oldValue是否可以响应count方法来check。但是,不是很确定这个结论。