Substituting JSON null values in Mantle

3.9k views Asked by At

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?

3

There are 3 answers

0
Andrew Ebling On

I had incorrectly assumed NSNull would be generated for a null JSON value. In fact it is parsed to a nil value.

So the solution is to check inObj against nil, rather than NSNull:

+ (NSValueTransformer *)foobarJSONTransformer {
return [MTLValueTransformer transformerWithBlock:^id(id inObj) {
    if (inObj == nil) {
        return [NSNumber numberWithInteger: -1];
    } else {
        return inObj;
    }
}];

the substitution will then work as expected.

0
Mani On

If you received as null, it will generated as NSNull. But if they missed this field or send it as empty, it will generate as nil while parsing. so better you can use below code

if (inObj == nil || inObj == [NSNull null] )
0
Huanhoo On

create a base model and inherit MTLModel,and override blow code:

- (void)setNilValueForKey:(NSString *)key {
    [self setValue:@0 forKey:key];
}

if you property is oc object,it will be nil immediate,and can't execute the method.but it can execute if the property is int,bool or float.