5

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

2 Answers 2

9

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

(adding a bit of extra info) Not only do they NSLog as a string, but also [NSString stringWithFormat:@"%@",nullObj]; will output '<null>' in your app, which is why most people are misled by debugging this dataType.
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"]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.