【问题标题】:Swift 4 - Issue with ObjectMapper while parsing JSONSwift 4 - 解析 JSON 时 ObjectMapper 出现问题
【发布时间】:2017-10-03 15:39:46
【问题描述】:

我的代码在 Swift 4 之前运行良好,我只是在解析一个简单的 JSON 文件,并将所有内容映射到我的模型类中。

这是我的示例代码:

首先我得到我的 json 文件。

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

那我就可以解析了。

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

现在我可以向你展示我的 Zone 类

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"]
    }

您还需要我来查看我的 JSON 文件:

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

我崩溃了,因为 parsedZones 为零。 我知道我可以检查 nil 但它在 Swift 3 上工作,在转换为 Swift 4 之前我没有进行任何修改。 关于我的 JSON 文件,它不应该是 nil。

我可以帮忙吗?

【问题讨论】:

  • JSONEncoder/Decoder in Swift 4 使 ObjectMapper 几乎过时了;)
  • 你能说得更具体些吗@vadian?我很感兴趣
  • 请观看有关 Swift 和 Foundation 的新功能的 WWDC 视频。

标签: ios11 swift4 xcode9 objectmapper


【解决方案1】:

你必须像这样使用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    相关资源
    最近更新 更多