2015-01-13 59 views
4

我有這個問題。我正在Swift中開發應用程序,並使用RestKit來檢索數據並將其發佈回API。不過,我打了路障。如果檢索到的JSON有效載荷包含一些空值,該應用WIL崩潰與消息:RestKit JSON null值崩潰

***終止應用程序由於未捕獲的異常「NSInvalidArgumentException」,原因:「 - [NSNull長度]:無法識別的選擇發送到實例0x1994faba0 '

我該怎麼辦? 映射的屬性是字符串。

映射對象:

public class User: NSObject { 

    public var id: Int? = 0 
    public var email: String? 
    public var firstName: String? 
    public var lastName: String? 
    public var name: String? 
    public var office: String? 
    public var phone: String? 
    public var company: String? 

} 

映射:

let userMapping = RKObjectMapping(forClass: User.self) 
userMapping.addAttributeMappingsFromDictionary([ 
    "id": "id", 
    "email": "email", 
    "first_name": "firstName", 
    "last_name": "lastName", 
    "name": "name", 
    "company": "company", 
    "phone": "phone", 
    "office": "office", 
]) 
let responseDescriptor = RKResponseDescriptor(mapping: userMapping, pathPattern: currentUserPath, keyPath: "data", statusCodes: NSIndexSet(index: 200)) 
objectManager.addResponseDescriptor(responseDescriptor) 

JSON響應:

{ 
    "status": "ok", 
    "data": { 
    "id": 1, 
    "email": "[email protected]", 
    "created_at": 1418832714451, 
    "updated_at": 1421077902126, 
    "admin": true, 
    "first_name": "John", 
    "last_name": "Doe", 
    "company": null, 
    "office": null, 
    "phone": null, 
    "name": "John Doe" 
    } 
} 

它崩潰對這些的:辦公,電話和姓名。

+1

顯示JSON和您的映射。改進JSON。將NSNull的處理添加到您的代碼中。 – Wain

+0

我編輯了我的問題以滿足您的請求:)如何使用RestKit處理NSNull? –

+0

你使用什麼版本(它應該轉換爲零) – Wain

回答

0

嘗試使用其他版本的RestKit。 RestKit代碼庫中有關於空值綁定的更改。

+0

我確實嘗試過舊版本,它在JSON中將null映射爲無,Swift/Obj-C –

+0

@ZdeněkTopič你能告訴哪個版本? –

0

@Hotlicks是正確的,空值應該由客戶端處理。我相信這次崩潰的原因是Restkit無法正確內省Swift中的類屬性類型。我們通過將明確的targetClass添加到我們的RKObjectMapping中來解決這個問題。因此,而不是使用addAttributeMappingsFromDictionary方法,嘗試:

let userMapping = RKObjectMapping(forClass: User.self) 
let simpleMapping = RKAttributeMapping(fromKeyPath: "first_name", toKeyPath: "firstName") 
simpleMapping.propertyValueClass = NSString.classForCoder() // we used class for coder when we did our project, but you might have success with something else. 
userMapping.addPropertyMapping(simpleMapping) 

你要做的關係也是相同的,就像這樣:

let relationshipMapping = RKRelationshipMapping(fromKeyPath: "person", toKeyPath: "person", withMapping: Person.self) 
relationshipMapping.propertyValueClass = Person.classForCoder() 
userMapping.addPropertyMapping(relationshipMapping) 

這使得從NSNull自動轉換成Swift可選。