سؤال

I am using JSON-RPC to communicate between iOS application and the server. Some return values of the server are optional.

Considering the combination of technologies I am using, is it better to return these null values like {"telephone": null} or by completely omitting the "telephone" element in the response?

Futher explanation of what I am asking:

It doesn't look like the JSON-RPC spec specifies much to do with the method result (please correct me if I'm wrong) and clearly not sending loads null elements would improve performance and reduce bandwidth somewhat. What I'm most interested in though is the best approach from an iOS NSJSONSerialization perspective. Is it easier/better to check for whether a key exists in an NSDictionary or whether an existing key has a null value?

هل كانت مفيدة؟

المحلول

First of all {"telephone": "null"} is not a null value. There are quotes so actually telephone property has string value with text "null". Server needs to send {"telephone": null} - without quotes. I'd go with listing all relevant properties that your app needs in response and put null as a value if there is not value. Then you can easily check in NSDictionary you get from NSJSONSerialization if value for key is NSNull.

if ([dictionaryValue isKindOfClass:[NSNull class]])
    myThink.myProperty = nil;

نصائح أخرى

I'm using a completely different technique, somewhat unorthodox for sure, since my code is dealing with huge data sets and I really hate having to make tests for NSNull on each value. What I did was subclass NSNull, so when dealing with data, I can test if its numeric value is 0, if its string length is 0, etc.

@implementation NSNull (JSON)

- (NSUInteger)length { return 0; }

- (NSInteger)integerValue { return 0; };

- (CGFloat)floatValue { return 0; };

- (NSString *)description { return @"0(null)"; } // so I know it was NSNull in log messages

- (NSArray *)componentsSeparatedByString:(NSString *)separator { return @[]; }

- (id)objectForKey:(id)key { return nil; }

- (BOOL)boolValue { return NO; }

@end

EDIT: I used this exact same code in an e-commerce shipping app. There were literally thousands of objects getting returned by tens of different APIs - having to look at each item to see if it was [NSNull null] would have been a nightmare. I tried to write a routine to groom results, it would recursively look at dictionaries and arrays and reconstruct the object, but it got too complicated.

In any case, I never even once had an issue with this solution. Obviously YMMV.

I've packed the check in a function, if anyone interested.

-(id)checkNull:(id)object{
    if([object isKindOfClass:[NSNull class]])return nil;
    else return object;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top