2013-02-19 47 views
3

我正在使用NSJSONSerializationJSON文檔轉換爲Core Foundation類型。NSJSONSerialization unboxes NSNumber?

我在我的JSON這是一個「數字」字段。有時是整數,有時是浮點數。

現在,問題是當NSJSONSerialization將我的JSON變成NSDictionary,我嘗試使用objectForKey提取數字,有時它是一個int,有時它是一個double。看起來NSJSONSerialization並不是簡單地將它留在NSNumber包裝中,而是實際取消裝箱值,並將插入到NSDictionary中。

很奇怪。我以爲你應該把原始信息放入NSDictionary。所以我現在的問題是我不知道我應該投射什麼類型(int或double)來保存實際的數值。

有人知道出路嗎?

+1

不,它不能這樣做,因爲你只能將對象存儲在'NSDictionary'中,所以它必須保持它們裝箱。 – trojanfoe 2013-02-19 13:58:41

+0

奇怪吧?但這正是發生了什麼!我正在使用AFNetwroking(它使用NSJSONSerialization底層),如果這有所作爲。 – elsurudo 2013-02-19 14:03:29

回答

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 
} 

+0

因爲這將是一個解決方案,如果我的問題成爲一個真正的問題,我會將其標記爲正確的。 – elsurudo 2013-02-19 14:26:41

0

原來他們NSNumbers一直以來,我在調試只是沒有經驗。我只是感到困惑,並認爲它們是int和double值,因爲這是調試器呈現它們的方式。所以這是調試器,拆箱,而不是NSJSONSerialization ...