Swift ObjectMapper - 数组映射

时间:2017-11-10 07:51:35

标签: swift

我有一个JSON响应,如:

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

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

我创建了我的对象模型并使用objectMapper来映射/解析这个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
    }

使用print(item)我可以看到对象,但是我无法进行附加工作。它给出了“Unexpectedly found nil while unwrapping an Optional value”错误。

2 个答案:

答案 0 :(得分:1)

您的JSON无效。

例如,您可以使用JSONLint检查您的JSON有效性。

为了提高代码的安全性,请避免使用!

替换

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

通过

if let author = (Mapper<Author>().map(JSONObject: item) {
    authorArray.append(author) 
} else {
    print("Unable to create Object from \(item)")
}

答案 1 :(得分:0)

你有无效的JSON,
根据你的json 作者字典作者字典没有

除了内部数组,还有字典,但没有括号和逗号

您的正确JSON是

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

     ]

然后你的代码对我来说没问题

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

修改

试试这个

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