While using Mantle, is there a possibility to before returning the object we are creating (on this case via JSON) to verify that X and Y properties are not nil?
Imagine this class:
@interface Person : MTLModel <MTLJSONSerializing>
@property(nonatomic,strong,readonly)NSString *name;
@property(nonatomic,strong,readonly)NSString *age;
@end
I want a way to verify that if the JSON I received doesn't have the name
(for some reason there was an issue on server's DB) I will return a nil
Person, as it doesn't make sense to create that object without that property set.
Whilst you could override the initialiser. It seems more concise to override the validate:
as this is called at the last stage before Mantle
returns the deserialised object. Makes sense to put all your validation logic in a validate
method...
See the final line of the MTLJSONAdapter
id model = [self.modelClass modelWithDictionary:dictionaryValue error:error];
return [model validate:error] ? model : nil;
This tells us that if our custom model returns NO
from validate
, then Mantle will discard the object.
So you could in your subclass simply perform the following:
- (BOOL)validate:(NSError **)error {
return [super validate:error] && self.name.length > 0;
}
Ideally in your own implementation you probably want to return an appropriate error.
The validate method will then call Foundation's validateValue:forKey:error:
for every property that you registered with Mantle in JSONKeyPathsByPropertyKey
. So if you want a more controlled validation setup you could also validate your data here..
You can use the MTLJSONSerializing
protocol method classForParsingJSONDictionary:
to return nil rather than an invalid object:
// In your MTLModelSubclass.m
//
+ (Class)classForParsingJSONDictionary:(NSDictionary *)JSONDictionary {
if (JSONDictionary[@"name"] == nil || JSONDictionary[@"age"] == nil) {
return nil;
}
return self.class;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With