6

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

Carpetfizz
  • 8,707
  • 22
  • 85
  • 146

2 Answers2

10

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
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • (adding a bit of extra info) Not only do they NSLog as a string, but also `[NSString stringWithFormat:@"%@",nullObj];` will output '' in your app, which is why most people are misled by debugging this dataType. – Chris J May 05 '16 at 22:27
1

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"]);
iphonic
  • 12,615
  • 7
  • 60
  • 107