Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift ObjectMapper - array mapping

Tags:

swift

I have a JSON response like:

      {
        total_count: 155,
        size: 75,
        authors: [{ name: "test1"
                    id: 1

                 },
                 {name: "test2"
                    id: 2
                 }]
      }

I created my object model and use objectMapper for mapping/parsing this json.

import Foundation
import SwiftyJSON
import ObjectMapper

class Author: Mappable {
    var id: Int!
    var name: String!

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        self.id <- map["id"]
        self.name <- map["name"]
    }

    static func fromJSONArray(_ json: JSON) -> [Author] {
        var authorArray: [Author] = []
        if json.count > 0 {
            for item in json["authors"]{
                print(item)
                authorArray.append(Mapper<Author>().map(JSONObject: item)!)
            }
        }
        return authorArray
    }

With print(item) I can see the objects but, I can't make append work. It is giving "Unexpectedly found nil while unwrapping an Optional value" error.

like image 252
serdar aylanc Avatar asked Nov 07 '22 14:11

serdar aylanc


1 Answers

Your JSON is not valid.

You can check your JSON validity using JSONLint for exemple.

For more safety in your code, avoid usage of !.

Replace

authorArray.append(Mapper<Author>().map(JSONObject: item)!)

by

if let author = (Mapper<Author>().map(JSONObject: item) {
    authorArray.append(author) 
} else {
    print("Unable to create Object from \(item)")
}
like image 111
CZ54 Avatar answered Dec 10 '22 17:12

CZ54