我使用NSJSONSerialization将JSON文档转换为Core类型。
我的JSON中有一个字段是“数字”。有时是整数,有时是浮点数。
现在,问题是当NSJSONSerialization将我的JSON转换为NSDictionary时,我尝试使用objectForKey提取数字,有时是int,有时是双倍。NSJSONSerialization似乎不只是简单地将其放在NSNumber包装器中,而是实际上将该值解压缩并插入到NSDictionary中。
很奇怪。我以为我们应该把原语放到NSDictionary里。因此,我现在遇到的问题是,我不知道应该使用哪种类型(int或double)来保存实际的数字值。
有谁知道出路吗?
发布于 2013-02-19 14:13:57
您可以从NSNumber获取基元类型。只需使用以下代码片段:
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
}等等。
发布于 2013-02-19 14:16:34
原来他们一直都是NSNumbers,而我只是缺乏调试的经验。我只是感到困惑,认为它们是int值和双值值,因为调试器就是这样显示它们的。所以是调试器解除了装箱,不是NSJSONSerialization.
https://stackoverflow.com/questions/14959282
复制相似问题