ios JSON映射对象

时间:2018-05-29 08:12:54

标签: ios json swift objectmapper

我正在使用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>())

}

}

这是我的作者类:

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对象时,我的所有书籍都会保存给作者...

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您是否尝试过不使用中间map实体进行映射?字符串数组映射应该可以正常工作。 查看https://github.com/Hearst-DD/ObjectMapper#objectmapper--realm

此外,currentKey具有currentValueAuthor属性,这些属性可能包含您需要使用DateTime实体使用的内容。

答案 1 :(得分:0)

非常感谢。 它适用于:

  if let tmpAuthors = map.JSON[SerializationKeys.authors] as? [String] {
        for author in tmpAuthors {
            let authorObject = Author()
            authorObject.authorName = author
            authors.append(authorObject)
        }
    }