问题
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
回答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"]);
回答2:
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
}
来源:https://stackoverflow.com/questions/24400789/nsjsonserialization-returns-null-string