RestKit JSON null值崩溃

我有这个问题。 我正在Swift中开发应用程序并使用RestKit检索并将数据发布回API。 但是我遇到了路障。 如果检索到的JSON有效负载包含一些空值,应用程序将崩溃并显示以下消息:

***由于未捕获的exception’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可选。