问题描述
我正在使用NSJSONSerialization
将JSON
文档转换为Core Foundation类型.
I'm using NSJSONSerialization
to turn a JSON
document into the Core Foundation types.
我的JSON
中有一个字段是数字".有时是整数,有时是浮点数.
I have a field in my JSON
which is a "number". It's sometimes and integer, sometimes a float.
现在,问题是当NSJSONSerialization
将我的JSON
转换为NSDictionary
时,我尝试使用objectForKey提取数字,有时是int,有时是double.似乎NSJSONSerialization
并不只是将其保留在NSNumber
包装器中,而是实际上将值拆箱,然后将 that 插入到NSDictionary
中.
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
.
很奇怪.我以为您应该将基元放入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.
有人知道出路吗?
推荐答案
您可以从NSNumber获取原始类型.只需使用以下代码段即可:
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
}
等等.
这篇关于NSJSONSerialization取消开箱NSNumber吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!