【问题标题】:RESTKIT : deserialize JSON with not all relationship attributeRESTKIT:反序列化 JSON 与并非所有关系属性
【发布时间】:2015-04-09 21:59:51
【问题描述】:

我尝试像这样反序列化 JSON:

{"id":1234, "content": "Hi, This is a message", "dateSaved":"10/04/2015 11:00", "user":{"id":12}}

型号:

class Message: NSManagedObject {
    @NSManaged var content: String
    @NSManaged var dateSaved: NSDate
    @NSManaged var id: NSNumber
    @NSManaged var user: User
}

class User: NSManagedObject {
    @NSManaged var id: NSNumber
    @NSManaged var login: String
    @NSManaged var mobile: String
    @NSManaged var password: String
    @NSManaged var picture: NSData
    @NSManaged var messages: NSSet
}

用户已经保存在 iOS 数据库中,所以我不需要从服务器发送它的所有数据。问题是RKRelationshipMappingRKConnectionDescription 似乎都不适用于这种工作:第一个工作是完整的对象,可以直接由CoreData 操作;第二个只能与标识符一起使用,不能与对象一起使用

我无法更改服务器将对象序列化为 JSON 的方式,因为其他 Android 应用可以使用这种 JSON

有人知道如何解决这个问题吗?

【问题讨论】:

  • 显示您的代码和模型并解释映射不起作用的原因

标签: ios json swift restkit


【解决方案1】:

好的,我想通了。我刚刚忘记为RKRelationshipMapping 设置方法addAttributeMappingsFromDictionary

let messageAttributesMapping = [
    "id":  "id",
    "content":  "content",
    "dateSaved":  "dateSaved"
]

extension Message {
    class func mappingResponse(managedObjectStore: RKManagedObjectStore) -> RKMapping {
        let messageMapping = RKEntityMapping(forEntityForName: "Message", inManagedObjectStore: managedObjectStore)

        messageMapping.identificationAttributes = ["id"]
        messageMapping.addAttributeMappingsFromDictionary(messageAttributesMapping)

        let userMapping = RKEntityMapping(forEntityForName: "User", inManagedObjectStore: managedObjectStore)
        userMapping.identificationAttributes = ["id"]
        userMapping.addAttributeMappingsFromDictionary(["id" : "id"])

        messageMapping.addPropertyMapping(RKRelationshipMapping(fromKeyPath: "user", toKeyPath: "user", withMapping: userMapping))

        return messageMapping
    }
}

这个解决方案可以反序列化 JSON,但我仍然想知道是否应该尝试使用 RKConnectionDescription,这似乎是为我们只有 id 的关系而构建的?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2017-04-06
    • 2014-07-31
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多