[英]ios JSON mapping object
我正在使用Swift开发iOS应用。
我使用RealmSwift,ObjectMapper和ObjectMapper_Realm从JSON文件中获取数据并将其保存在Realm中。 到目前为止,它工作正常,但是我得到了一个String数组,却没有在另一个对象的同一级别上提取键,而且我不知道该怎么做...
这是我的对象:
"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对象时,我所有的书都保存为作者...
谢谢你的帮助
您是否尝试过不使用中间Author
实体进行映射? 字符串数组映射应该可以正常工作。 查看https://github.com/Hearst-DD/ObjectMapper#objectmapper--realm 。
另外, map
具有currentKey
和currentValue
属性,其中可能包含您需要与Author
实体配合使用的属性。
非常感谢。 它可以很好地与:
if let tmpAuthors = map.JSON[SerializationKeys.authors] as? [String] {
for author in tmpAuthors {
let authorObject = Author()
authorObject.authorName = author
authors.append(authorObject)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.