簡體   English   中英

RestKit JSON null值崩潰

[英]RestKit JSON null value crash

我有這個問題。 我正在Swift中開發應用程序並使用RestKit檢索並將數據發布回API。 但是我遇到了路障。 如果檢索到的JSON有效負載包含一些空值,應用程序將崩潰並顯示以下消息:

***由於未捕獲的異常'NSInvalidArgumentException'終止應用程序,原因:' - [NSNull length]:無法識別的選擇器發送到實例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": "some@email.com",
    "created_at": 1418832714451,
    "updated_at": 1421077902126,
    "admin": true,
    "first_name": "John",
    "last_name": "Doe",
    "company": null,
    "office": null,
    "phone": null,
    "name": "John Doe"
  }
}

它崩潰了:辦公室,電話和名字。

嘗試使用另一個版本的RestKit。 RestKit代碼庫中有關null值綁定的更改。

@Hotlicks是對的,空值應該由客戶端處理。 我相信這次崩潰的原因是Restkit無法正確地反省Swift中的類屬性類型。 我們在項目中通過向RKObjectMapping添加顯式targetClass來解決這個問題。 因此,不要使用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可選。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM