Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substituting JSON null values in Mantle

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?

like image 282
Andrew Ebling Avatar asked Jan 08 '14 08:01

Andrew Ebling


3 Answers

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.

like image 167
Andrew Ebling Avatar answered Nov 15 '22 04:11

Andrew Ebling


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] )
like image 32
Mani Avatar answered Nov 15 '22 03:11

Mani


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.

like image 1
Huanhoo Avatar answered Nov 15 '22 02:11

Huanhoo