Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get AFNetworking to automatically parse NULL to nil?

We're using AFNetworking in our mobile app and a lot of times we will have JSON come back that has null for some values.

I'm getting tired of doing the following.

if ([json objectForKey:@"nickname"] isKindOfClass:[NSNull class]]) {
    nickname = nil;
} else {
    nickname = [json objectForKey:@"nickname"];
}

Anything we can do to make AFNetworking automagically set objects to nil or numbers to 0 if the value is null in the JSON response?

like image 712
birarda Avatar asked May 22 '12 00:05

birarda


3 Answers

You can set flag setRemovesKeysWithNullValues to YES in AFHTTPSessionManager response serializer:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithBaseURL:url sessionConfiguration:config];
AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
[serializer setRemovesKeysWithNullValues:YES];
[manager setResponseSerializer:serializer];
like image 66
DV_ Avatar answered Nov 03 '22 16:11

DV_


It's not really possible, since the dictionary can't contain nil as the object for a key. The key would have to be left out entirely in order to get the behavior you'd want, which would be undesirable in its own way.

Suppose you didn't have control over the data you were receiving and didn't know what keys were present in the JSON. If you wanted to list them all, or display them in a table, and the keys for null objects were left out of the dictionary, you'd be seeing an incorrect list.

NSNull is the "nothing" placeholder for Cocoa collections, and that's why it's used in this case.

You could make your typing a bit easier with a macro:

#define nilOrJSONObjectForKey(JSON_, KEY_) [[JSON_ objectForKey:KEY_] isKindOfClass:[NSNull class]] ? nil : [JSON_ objectForKey:KEY_]

nickname = nilOrJSONObjectForKey(json, @"nickname");
like image 37
jscs Avatar answered Nov 03 '22 17:11

jscs


DV_'s answer works great for AFHTTPSessionManager. But if you are using AFHTTPRequestOperation instead of the manager, try this:

AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
serializer.removesKeysWithNullValues = YES;
op.responseSerializer = serializer;
like image 2
gavdotnet Avatar answered Nov 03 '22 15:11

gavdotnet