Swift ObjectMapper - display an array

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 used objectMapper to match / parse 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 objects, but I can not execute the add command. He gives the error " Unexpectedly found nil while unwrapping an Optional value".

+4
source share
2 answers

Your JSON is invalid.

You can verify your JSON validity using JSONLint .

For greater security in code, avoid use !.

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)")
}
+1
source

You have invalid JSON,
According to your json the authors are a dictionary , but the author’s dictionary is missing

As well as inside the array there is a dictionary, but there are no brackets and a comma

Your correct json

authors: [ 
       {
        name: "",
        id: 0
       }

     ]

And then your code looks fine to me

   if json.count > 0 {
        for item in json["authors"]{
            print(item)
            authorArray.append(Mapper<Author>().map(JSONObject: item)!)
        }
    }

EDIT

try it

      if json.count > 0 {
            for item in json["authors"]{
                print(item)
                 do {
                   let objectData = try JSONSerialization.data(withJSONObject: item, options: .prettyPrinted)
                  let string = String(data: objectData, encoding: .utf8)
                authorArray.append(Mapper<Author>().map(JSONObject: string)!)

                  } catch {
                     print(error)
                   }
            }
        }
0
source

Source: https://habr.com/ru/post/1689042/


All Articles