【问题标题】:NSJSONSerialization unboxes NSNumber?NSJSONSerialization 拆箱 NSNumber?
【发布时间】:2013-02-19 13:57:00
【问题描述】:

我正在使用NSJSONSerializationJSON 文档转换为Core Foundation 类型。

我的JSON 中有一个字段,它是一个“数字”。它有时是整数,有时是浮点数。

现在,问题是当NSJSONSerialization 将我的JSON 变成NSDictionary 并且我尝试使用objectForKey 提取数字时,有时它是一个int,有时它是一个double。似乎NSJSONSerialization 并没有简单地将它留在NSNumber 包装器中,而是实际上将值拆箱,并将 that 插入到NSDictionary 中。

很奇怪。我以为你我们应该将原语放入NSDictionary。所以我现在遇到的问题是我不知道应该转换为什么类型(int 或 double)来保留实际的数值。

有人知道出路吗?

【问题讨论】:

  • 不,它不能这样做,因为您只能将对象存储在 NSDictionary 中,因此必须将它们装箱。
  • 很奇怪,对吧?但这正是正在发生的事情!我正在使用 AFNetwroking(它在后台使用 NSJSONSerialization),如果这有所作为的话。

标签: ios json nsjsonserialization


【解决方案1】:

您可以从 NSNumber 获取原始类型。只需使用以下代码 sn-p:

    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
}

等等

【讨论】:

  • 如果我的问题是一个真正的问题,这将是一个解决方案,我将把它标记为正确。
【解决方案2】:

原来它们一直都是 NSNumbers,而我只是缺乏调试经验。我只是感到困惑,并认为它们是 int 和 double 值,因为这就是调试器呈现它们的方式。所以拆箱的是调试器,而不是 NSJSONSerialization...

【讨论】:

    猜你喜欢
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    相关资源
    最近更新 更多