Home > Blockchain >  Swift - ObjectMapper: Mapping jsonString
Swift - ObjectMapper: Mapping jsonString

Time:03-07

I have two models:

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
}

}

and

class CellModelArray: StaticMappable {

var cells = [CellModel]()

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

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

}

I created a jsonString from object like this:

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

and json looks like this:

{"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}]}

Then I want to take this string and convert it back to the object, but when I try it like that:

var cells = CellModelArray()

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

it does not work and returns nil. Thank you for your help.

CodePudding user response:

Please drop ObjectMapper.

It's a library of merit but since Swift 4 (introduced 2017) it has become obsolete in favor of the built-in and swiftier Codable protocol.

The main benefit is that the model files can be structs (value types) and it's much more reliable because the developer doesn't have to take care of literal string keys

This is sufficient

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

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

The given JSON string

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}]}
"""

can be decoded and encoded with this code

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)
}
  • Related