json转model,是个开发都会遇到过。都已经9102年了,谁还不会用个第三方框架搞。拿起键盘就是干!json
啥?返回的字段值不是咱们所需的 在平常开发中,常常会遇到一些接口字段返回的值,并非我所须要的类型的状况,这个时候,咱们都会对这个字段进行处理。 举个栗子:bash
/** 错误代码 */
@property (nonatomic, assign) NSInteger error_code;
/** 错误消息 */
@property (nonatomic, copy) NSString *error_msg;
/** 是否成功 */
@property (nonatomic, assign) BOOL isSuccess;
复制代码
接口的json中的error_code字段,接口会用这个字段告诉我此次请求是否成功。比方说成功的error_code是1,平时咱们为了方便开发,会在model里本身加一个自定义的属性isSuccess,来表示本次网络请求回来以后的结果是否成功。一般的作法,要么重写error_code的set方法,在set的时候,作一次error_code==1的判断,将判断的结果,赋值给isSuccess,要么就重写isSuccess的get方法,get的时候,返回error_code==1的结果。 相信这些对于老司机们而言,都属于常规操做了。那咱们来看看坑在什么地方?网络
咱们来看这个案例: 接口返回了4个字段值,每一个字段都用获得,因此新建一个model类来解析。架构
@interface ExamSubjectVo : NSObject
/** 考试学科ID */
@property (nonatomic, assign) NSInteger examSubjectValue;
/** 考试学科名称 */
@property (nonatomic, strong) NSString *examSubjectName;
/** 学科分数 */
@property (nonatomic, strong) NSString *subjectScore;
/** 基础学科Id */
@property (nonatomic, assign) NSInteger subjectBaseId;
@end
复制代码
可是因为有业务需求,且为了方便开发过程区分,须要对考试名称的字段examSubjectName为全科或者语数外的状况,要特殊处理。因此,按照一向的思惟,咱们要重写set方法框架
- (void)setExamSubjectName:(NSString *)examSubjectName{
_examSubjectName = examSubjectName;
if ([examSubjectName isEqualToString:@"全科"]) {
self.subjectBaseId = -100;
}
if ([examSubjectName isEqualToString:@"语数外"]) {
self.subjectBaseId = -200;
}
}
复制代码
乍一看,也没什么问题,解析的过程当中,把字段的值转化为咱们须要的。并且真机实测的时候,全部的测试机都没问题,除了一台iPhone5以外 就除了一台iPhone5,debug的时候看到set方法确实也走了,但是最终的subjectBaseId并无转化成-100或者-200,可见subjectBaseId又被json自己的值覆盖了,也就是说 set方法的执行顺序,在不一样CPU架构设备上存在差别。测试
那么如何解决问题呢? 正是由于存在这样的差别,因此咱们只能在model全部的字段所有set完毕以后,再作一些特殊的字段处理,那么如何来处理呢? 翻阅YYModel源码,确定能有所发现,果不其然,有所收获。ui
/**
If the default json-to-model transform does not fit to your model object, implement
this method to do additional process. You can also use this method to validate the
model's properties. @discussion If the model implements this method, it will be called at the end of `+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`. If this method returns NO, the transform process will ignore this model. @param dic The json/kv dictionary. @return Returns YES if the model is valid, or NO to ignore this model. */ - (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic; 复制代码
YYModel提供了这么个方法,它会在+modelWithJSON:
, +modelWithDictionary:
, -modelSetWithJSON:
and -modelSetWithDictionary:
方法结束的时候调用。 因此咱们对model特殊字段的处理,都应该放到这个方法去执行this
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic{
if ([self.examSubjectName isEqualToString:@"全科"]) {
self.subjectBaseId = -100;
}
if ([self.examSubjectName isEqualToString:@"语数外"]) {
self.subjectBaseId = -200;
}
return YES;
}
复制代码
这么一来,问题就解决了。 注意,YYModel还有一个- (NSDictionary *)modelCustomWillTransformFromDictionary:(NSDictionary *)dic;
这个方法很相似,可是执行的时机不同,这个方法是在model转化以前执行,虽不符合本案例的需求,可是颇有可能在其余相似的状况能用的上。atom