0

更新

最后Unbox图书馆的作者回答了我的问题。 https://github.com/JohnSundell/Unbox/issues/156


我正在尝试Unbox使用. 来自服务器的响应具有这种结构。RealmListJSON

[
  {
    "name": "bla bla",
    "desc": "bla bla",
    "sequential": true,
    "createdAt": "2017-01-23T09:58:05.095Z",
    "hmImages": [
      {
        "urlBase": "https://blabla.com",
        "fullresPath": "/blaPath/iyba783fR81L8y.jpg",
        "id": "bla bla"
      },
      {
        "urlBase": "https://blabla.com",
        "fullresPath": "/blaPath/iyba783fR81L8y.jpg",
        "id": "bla bla"
      }
    ],
    "tags": [],
    "id": "bla bla"
  },
  {
    "name": "bla bla",
    "desc": "bla bla",
    "sequential": true,
    "createdAt": "2017-01-23T09:58:05.095Z",
    "hmImages": [
      {
        "urlBase": "https://blabla.com",
        "fullresPath": "/blaPath/iyba783fR81L8y.jpg",
        "id": "bla bla"
      }
    ]
    "tags": [],
    "id": "bla bla"
  }
]

请注意,根对象是一个Array字典。每个字典都有一个Array图像字典。

保存对象的类Realm如下所示:

// MARK: - Realm
final class Challenge: Object {

    dynamic var id = ""
    dynamic var name = ""
    dynamic var desc = ""
    dynamic var sequential = false
    dynamic var createdAt = Date()
    dynamic var btPlayground = ""

    // Relations
    let hmImages = List<Image>()
    let tags = List<Tag>()

    override static func primaryKey() -> String? {
        return "id"
    }

}

// MARK: - Unboxable
extension Challenge: Unboxable {

    convenience init(unboxer: Unboxer) throws {
        self.init()

        // Date formatter
        let dateFormatter = ISODateFormatter()

        id = try unboxer.unbox(key: "id")
        name = try unboxer.unbox(key: "name")
        desc = try unboxer.unbox(key: "desc")
        sequential = try unboxer.unbox(key: "sequential")
        createdAt = try unboxer.unbox(key: "createdAt", formatter: dateFormatter)
        btPlayground = try unboxer.unbox(key: "btPlayground")

    }

}

密钥路径出现问题hmImagesUnbox无法自动解析,我需要一种方法来做到这一点。

我尝试过UnboxableByTransform这样的事情:

extension List<T>: UnboxableByTransform {

    public typealias UnboxRawValue = [[String:Any]]

    public static func transform(unboxedValue: Array<[UnboxableDictionary]>) -> List<T>? {


    }

}

但没有用。任何想法?

谢谢!

4

1 回答 1

-1

你只是做错了。对于 json,请阅读此处

如果你坚持自己的方式。您应该考虑到 Realm 不接受Any您在 中public typealias UnboxRawValue = [[String:Any]]使用的类型,您只能使用 Realm 列出的类型。即 Bool、Int8、Int16、Int32、Int64、Double、Float、String、NSDate 和 NSData。

于 2017-01-25T12:53:07.213 回答