【发布时间】:2018-05-29 08:12:54
【问题描述】:
我正在使用 Swift 开发 iOS 应用程序。
我使用 RealmSwift、ObjectMapper 和 ObjectMapper_Realm 从 JSON 文件中获取数据并将其保存在 Realm 中。 到现在为止它工作得很好,但是我得到了一个字符串数组,而没有在另一个对象的同一级别提取键,我不知道该怎么做......
这是我的对象:
"books":
[
{
"id": 56436886,
"type": "Book",
"title": "Title of the book",
"authors": [
"Name FirstName",
]
}
]
这是我的映射类:
class Book: Object, Mappable {
// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let id = "id"
static let type = "type"
static let title = "title"
static let authors = "authors"
}
// MARK: Properties
@objc dynamic var id: Int = 0
@objc dynamic var type: String?
@objc dynamic var title: String?
var authors = List<Author>()
// MARK: ObjectMapper Initializers
/// Map a JSON object to this class using ObjectMapper.
///
/// - parameter map: A mapping from ObjectMapper.
convenience required init?(map: Map) {
self.init()
}
// MARK: - Model meta informations
override class func primaryKey() -> String? {
return "id"
}
override class func ignoredProperties() -> [String] {
return []
}
/// Map a JSON object to this class using ObjectMapper.
///
/// - parameter map: A mapping from ObjectMapper.
public func mapping(map: Map) {
id <- map[SerializationKeys.id]
type <- map[SerializationKeys.type]
title <- map[SerializationKeys.title]
authors <- (map[SerializationKeys.authors], ListTransform<Author>())
}
}
这是我的 Author 类:
class Author: Object, Mappable {
@objc dynamic var authorName: String?
// MARK: - Model meta informations
override class func primaryKey() -> String? {
return "authorName"
}
convenience required init?(map: Map) {
self.init()
}
func mapping(map: Map) {
self.authorName <- map
}
}
我不知道如何在 Author 类中进行映射,所以当我得到我的 JSON 对象时,我所有的书都会保存给作者...
感谢您的帮助
【问题讨论】:
标签: ios json swift objectmapper