更新
最后
Unbox
库的作者回答了我的问题。 https://github.com/JohnSundell/Unbox/issues/156
我尝试使用Unbox
使用Realm
将List
对象与其他相关对象放在一起。来自服务器的JSON
响应具有此结构。
[
{
"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"
}
]
请注意,root对象是字典的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")
}
}
hmImages
密钥路径出现问题。 Unbox
无法自动解析,我需要一种方法来执行此操作。
我尝试了UnboxableByTransform
这样的事情:
extension List<T>: UnboxableByTransform {
public typealias UnboxRawValue = [[String:Any]]
public static func transform(unboxedValue: Array<[UnboxableDictionary]>) -> List<T>? {
}
}
但没有奏效。 有什么想法吗?
谢谢!
答案 0 :(得分:-1)
你只是以错误的方式做到这一点。对于json,请阅读here。
如果你坚持自己的方式。你应该考虑到Realm不接受你在Any
中使用的public typealias UnboxRawValue = [[String:Any]]
类型,你只能使用Realm列出的类型。这是Bool,Int8,Int16,Int32,Int64,Double,Float,String,NSDate和NSData。