3

我正在使用NSJSONSerializationJSON文档转换为核心基础类型。

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

现在,问题是当NSJSONSerializationJSON变成 anNSDictionary并且我尝试使用 objectForKey 提取数字时,有时它是一个 int,有时它是一个 double。它似乎NSJSONSerialization不仅仅是将它留在NSNumber包装器中,而是实际上将值拆箱,并将其插入NSDictionary.

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

有人知道出路吗?

4

2 回答 2

3

您可以从 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-19T14:13:57.177 回答
0

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

于 2013-02-19T14:16:34.757 回答