Swift - ObjectMapper:映射 jsonString

Swift - ObjectMapper: Mapping jsonString

我有两个模型:

class CellModel: StaticMappable {

static func objectForMapping(map: Map) -> BaseMappable? {
    return nil
}

func mapping(map: Map) {
    id <- map["id"]
    title <- map["title"]
    description <- map["description"]
}


private var id: Int
private var title: String
private var description: String

init(id: Int, title: String, description: String) {
    self.id = id
    self.title = title
    self.description = description
}

}

class CellModelArray: StaticMappable {

var cells = [CellModel]()

static func objectForMapping(map: Map) -> BaseMappable? {
    return nil
}

func mapping(map: Map) {
    cells <- map["cells"]
}

}

我从这样的对象创建了一个json字符串:

let jsonString = Mapper().toJSONString(rootModel, prettyPrint: false)

和 json 看起来像这样:

{"cells":[{"id":0,"title":"Header","description":"Description"},{"description":"Description","id":0,"title":"Header"},{"description":"Description","id":1,"title":"Header"},{"id":0,"title":"Header","description":"Description"},{"description":"Description","title":"Header","id":0}]}

然后我想获取这个字符串并将其转换回对象,但是当我这样尝试时:

var cells = CellModelArray()

cells = Mapper<CellModelArray>().map(JSONString: code) ?? CellModelArray()

它不起作用,returns 没有。谢谢你的帮助。

请放下ObjectMapper

这是一个优秀的图书馆,但自 Swift 4(2017 年推出)以来,它已经过时,取而代之的是 built-in 和 swiftier Codable协议。

主要的好处是模型文件可以是结构(值类型)并且它更可靠,因为开发人员不必处理文字字符串键

够了

struct Model: Codable {
    let cells : [Cell]
}

struct Cell: Codable {
    let id: Int
    let title: String
    let description: String
}

给定的JSON字符串

let jsonString = """
{"cells":[{"id":0,"title":"Header","description":"Description"},{"description":"Description","id":0,"title":"Header"},{"description":"Description","id":1,"title":"Header"},{"id":0,"title":"Header","description":"Description"},{"description":"Description","title":"Header","id":0}]}
"""

可以用这个码解码编码

do {
    // Decode the JSON
    let decoded = try JSONDecoder().decode(Model.self, from: Data(jsonString.utf8))
    print(decoded)

    // Encode it back
    let encoded = try JSONEncoder().encode(decoded)
    print(String(data: encoded, encoding: .utf8)!)
} catch {
    print(error)
}