NSJSONSerialization unboxes NSNumber?

I use NSJSONSerialization to turn a JSON document into Core Foundation types.

I have a field in my JSON that is a "number". This is sometimes an integer, sometimes floating.

Now the problem is that NSJSONSerialization turns my JSON into an NSDictionary , and I'm trying to extract a number using objectForKey, sometimes it is int and sometimes double. It seems that NSJSONSerialization does not just leave it in the NSNumber , but actually releases the value and inserts it into the NSDictionary .

Very strange. I thought you should put primitives in NSDictionary . So the problem that I am facing right now is that I do not know what type (int or double) I should use to store the actual value of the number.

Does anyone know a way out?

+3
source share
2 answers

You can get a primitive type from NSNumber. Just use the 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 } 

Etc.

+3
source

Turns out they were NSNumbers all the time, and I'm just inexperienced at debugging. I was just confused and thought it was int and double values, because that's how the debugger reports them. So the debugger that unpacked, not NSJSONSerialization ...

0
source

Source: https://habr.com/ru/post/953319/


All Articles