Search code examples
ios11swift4xcode9objectmapper

Swift 4 - Issue with ObjectMapper while parsing JSON


My code was working perfectly before Swift 4, I am just parsing a simple JSON file, and I am mapping everything into my model class.

Here is my example code :

First of all I get my json file.

if let path = Bundle.main.path(forResource: "myFile", ofType: "json") { }

Then I can parse it.

do {
       let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe)
       let json = JSON(data: jsonData)

       if let jsonZones = json["zones"].array {
          let parsedZones = Mapper<Zone>().mapArray(JSONObject: jsonZones.description)
          parsedZones?.forEach({ (element) -> Void in
              // Do stuff...
          })
 }

Now I can show you my Zone class

class Zone: Object, Mappable {

    @objc dynamic var code: String?

    required convenience init?(map: Map) {
        self.init()
        mapping(map: map)
    }

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

You will also need my to see my JSON file :

{
    "info": {
        ....
        ....
    },
    "zones": [{
        "code": "EN"
    }],
}

I am crashing because parsedZones is nil. I know I can check for nil but it was working on Swift 3 and I modified nothing before converting to Swift 4. Regarding my JSON file, it shouldn't be nil.

Can I have some help?


Solution

  • You have to use like this :

    if let jsonZones = json["zones"].arrayObject {
        let parsedZones = Mapper<Zone>().mapArray(JSONObject: jsonZones)
        parsedZones?.forEach({ (element) -> Void in
            print(element.code)
        })
    }