[英]How to handle unexpected data types with Mantle
In my MTLModel subclass I have this: 在我的MTLModel子类中,我有这样的:
@property (assign, nonatomic) NSInteger catId;
And of course this in the implementation: 当然这在实施中:
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"catId" : @"cat_id"
};
}
But what if my server friends decide to change cat_id to a string in the JSON response? 但是如果我的服务器朋友决定将cat_id更改为JSON响应中的字符串呢? How can I handle this case, and convert it to an int so that I don't get Mantle errors? 我如何处理这种情况,并将其转换为int,以便我不会得到Mantle错误?
We also used Mantle for quite some time, but at the end migrated to handwritten parser/serializers, as the task itself seem to be trivial. 我们也使用Mantle很长一段时间,但最后迁移到手写的解析器/序列化器,因为任务本身似乎是微不足道的。
Though, we also have this kind of problems: what if server return something we do not expect (eg NSDictionary
instead of NSString
). 虽然,我们也有这样的问题:如果服务器返回我们不期望的东西(例如NSDictionary
而不是NSString
)。
To prevent our app from crashing we use this simple tool: Fuzzer . 为了防止我们的应用崩溃,我们使用这个简单的工具: Fuzzer 。
Basically the tool provides a method that takes a sample and a block. 基本上该工具提供了一个采样和块的方法。 The block evaluates several times, each time bringing slightly mutated version of the sample. 该块会多次评估,每次都会带来轻微变异的样本。 You can check behaviour of the models/parsers/serializers using the mutants, to ensure that your code handles unexpected data gracefully. 您可以使用突变体检查模型/解析器/序列化程序的行为,以确保您的代码正常处理意外数据。
Here is example taken from project's README: 以下是项目自述文件中的示例:
- (void)test {
NSDictionary *sample = @{
@“name” : @“John Doe”,
@“age” : @42
};
UserDeserializer *deserializer = [UserDeserializer new];
FZRRunner *runner = [FZRRunner runnerWithBuiltinMutationsForSample:sample];
NSArray *reports = [runner enumerateMutantsUsingBlock:^(NSDictionary *mutant) {
[deserializer deserializeUser:mutant];
}];
XCTAssertEqual(reports.count, 0);
}
if([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")])
{
//if it is int or number
}
else
{
}
May be above method will help you 可能上面的方法会帮助你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.