3

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?

Dilip Manek
  • 9,095
  • 5
  • 44
  • 56
elsurudo
  • 3,579
  • 2
  • 31
  • 48
  • 1
    No, it can't do that as you can only store objects in a `NSDictionary` so it has to keep them boxed. – trojanfoe Feb 19 '13 at 13:58
  • Strange, right? But that's exactly what's happening! I am using AFNetwroking (which uses NSJSONSerialization under the hood), if that makes a difference. – elsurudo Feb 19 '13 at 14:03

2 Answers2

3

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.

Mark Kryzhanouski
  • 7,251
  • 2
  • 22
  • 22
  • Since this would have been a solution had my problem been a real problem, I'm going to mark this as correct. – elsurudo Feb 19 '13 at 14:26
0

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...

elsurudo
  • 3,579
  • 2
  • 31
  • 48