gpt4 book ai didi

Swift ObjectMapper - 数组映射

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:31 25 4
gpt4 key购买 nike

我有一个像这样的 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”错误。

最佳答案

您的 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)")
}

关于Swift ObjectMapper - 数组映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47218014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com