I'm using Mantle to parse some JSON which normally looks like this:
"fields": {
"foobar": 41
}
However sometimes the value of foobar is null:
"fields": {
"foobar": null
}
This causes MTLValidateAndSetValue
to throw an exception as it's trying to set a nil value via Key-Value Coding.
What I would like to do is detect the presence of this null value and substitute it with -1.
I tried overriding foobarJSONTransformer
in my MTLModel
subclass as follows:
+ (NSValueTransformer *)foobarJSONTransformer {
return [MTLValueTransformer transformerWithBlock:^id(id inObj) {
if (inObj == [NSNull null]) {
return [NSNumber numberWithInteger: -1];
} else {
return inObj;
}
}];
...and I can see this code being called but inObj is never equal to [NSNull null]
, hence the substitution doesn't happen and the exception is still thrown by Mantle.
What is the correct way to catch this JSON null case and do the substitution?
I had incorrectly assumed
NSNull
would be generated for a null JSON value. In fact it is parsed to anil
value.So the solution is to check
inObj
againstnil
, rather thanNSNull
:the substitution will then work as expected.