问题
I'm using NSJSONSerialization to turn a JSON document into the Core Foundation types.
I have a field in my JSON which is a "number". It's sometimes and integer, sometimes a float.
Now, the problem is when NSJSONSerialization turns my JSON into an NSDictionary and I try to extract the number using objectForKey, sometimes it's an int, and sometimes it's a double. It seems NSJSONSerialization doesn't simply leave it in an NSNumber wrapper, but actually unboxes the value, and inserts that into the NSDictionary.
Very strange. I thought you we're supposed to put primitives into an NSDictionary. So the problem I have now is that I don't know what type (int or double) I should be casting to to preserve the actual number value.
Anyone know a way out?
回答1:
You can get primitive type from NSNumber. Just use following code snippet:
const char* type = [theValue objCType];
if (strcmp (type, @encode (NSInteger)) == 0) {
//It is NSInteger
} else if (strcmp (type, @encode (NSUInteger)) == 0) {
//It is NSInteger
} else if (strcmp (type, @encode (int)) == 0) {
//It is NSUInteger
} else if (strcmp (type, @encode (float)) == 0) {
//It is float
} else if (strcmp (type, @encode (double)) == 0) {
//It is double
} else if (strcmp (type, @encode (long)) == 0) {
//It is long
} else if (strcmp (type, @encode (long long)) == 0) {
//It is long long
}
And etc.
回答2:
Turns out they were NSNumbers all along, and I am just inexperienced at debugging. I was just confused and thought they were int and double values, because that is how the debugger presents them. So it's the debugger that was unboxing, not NSJSONSerialization...
来源:https://stackoverflow.com/questions/14959282/nsjsonserialization-unboxes-nsnumber