【问题标题】:RestKit JSON null value crashRestKit JSON空值崩溃
【发布时间】:2015-03-11 02:40:38
【问题描述】:

我有这个问题。我正在用 Swift 开发应用程序并使用 RestKit 来检索数据并将其发布回 API。但是我遇到了路障。如果检索到的 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": "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"
  }
}

它会在以下各项中崩溃:办公室、电话和姓名。

【问题讨论】:

  • 显示 JSON 和您的映射。改进 JSON。将 NSNull 处理添加到您的代码中。
  • 我已经编辑了我的问题以满足您的要求 :) 如何使用 RestKit 自己处理 NSNull?
  • 你使用的是什么版本(它应该转换为 nil 真的)
  • RestKit 0.24.0,Xcode 6.1.1,iOS 8.1
  • 如果我从映射中删除公司、办公室和电话,它就可以正常工作。

标签: ios json swift restkit


【解决方案1】:

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

【讨论】:

  • 我确实尝试过旧版本,它将 JSON 中的 null 映射为 Swift/Obj-C 中的 nil
  • @ZdeněkTopič 你能告诉我哪个版本吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多