RestKit JSON null值崩溃

时间:2015-01-13 07:40:42

标签: ios json swift restkit

我有这个问题。我正在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"
  }
}

它崩溃了:办公室,电话和名字。

2 个答案:

答案 0 :(得分:0)

尝试使用其他版本的RestKit。 RestKit代码库中有关于空值绑定的更改。

答案 1 :(得分:0)

@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可选。