Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSJSONSerialization returns "<null>" string

I'm try to set an NSDictionary to a JSON object retrieved from the server, I'm doing that in this line:

_peopleArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

It works fine and properly creates the dictionary. However, I have a problem, values that are null in the JSON object are stored as "<null>" string values in the dictionary. Is there any way to fix this or work around it? I want to avoid traversing through the entire thing and setting them to @"".

Thanks for any help!

~Carpetfizz

like image 433
Carpetfizz Avatar asked Jun 25 '14 05:06

Carpetfizz


Video Answer


2 Answers

You are wrong. null values in JSON are not stored as <null> string values. They are stored as NSNull objects, which NSLog logs as <null>.

You can never trust what data you were given. If you assume you got an NSString and the server sends you a number, your code is likely to crash.

NSString* myJSONString = ...;
if ([myJSONString isKindOfClass:[NSString class]]) {
    it is a string
} else {
    it is not a string
}
like image 131
gnasher729 Avatar answered Oct 18 '22 03:10

gnasher729


There is nothing I guess, though it can be easily corrected from api makers, if not possible, you can always put a simple macro, I use to avoid such thing, follow macro below

#define Is_Empty(value) (value == (id)[NSNull null] || value == nil || ([value isKindOfClass:[NSString class]] && ([value isEqualToString:@""] ||  [value isEqualToString:@"<null>"]))) ? YES : NO

#define IfNULL(original, replacement) IsNULL(original) ? replacement : original

#define IsNULL(original) original == (id)[NSNull null]

#define SafeString(value) IfNULL(value, @"")

Usage

self.label.text=SafeString([dic objectForKey:@"name"]);
like image 21
iphonic Avatar answered Oct 18 '22 04:10

iphonic