【问题标题】:Parsing Failed: JSONDecoder Swift解析失败:JSONDecoder Swift
【发布时间】:2020-04-17 18:53:33
【问题描述】:

我正在尝试使用 Alamofire 5.2 解码 json 请求 问题是我使用 JSONDecoder 并且我有一些关于转换的问题

API 是西班牙语,我的模型是英语,所以我决定使用键的枚举来更改这种值

但我不知道这是否有效...这是我的代码:

API 响应:(json 变量)

    {
  "sistemaOperativoId" : 0,
  "nombreUsuario" : "Coasnf_09",
  "menus" : [

  ],
  "acciones" : [

  ],
  "fechaRegistro" : "2020-04-15T09:46:24.0573154",
  "empresa" : null,
  "version" : null
}

我的模特:

struct UserP: Decodable{
    var username : String
    var company : String

    private enum CodingKeys: String, CodingKey{
        case username = "nombreUsuario"
        case company = "empresa"
    }

    init(from decoder: Decoder) throws{
        let container = try decoder.container(keyedBy: CodingKeys.self)
        username = try container.decode(String.self, forKey: .username) ?? "null"
        company = try container.decode(String.self, forKey: .company)  ?? "null"
    }

    init(username: String, company: String){
        self.username = username
        self.company = company
    }
}

转换:

   func login(user: User) -> UserP? {
        var userData: UserP! = nil
        AF.request(UserRouter.login(user: user)).responseJSON{ response in
            switch response.result {
            case .success(let response):
                print(response)
                let dict = (response as? [String : Any])!
                let json = dict["data"] as! [String: Any]

                if let jsonData = try? JSONSerialization.data(withJSONObject: json , options: .prettyPrinted)
                {
                    do {
                        var jsonString = String(data: jsonData, encoding: String.Encoding.utf8)!
                        print(jsonString)
                        userData = try JSONDecoder().decode(UserP.self, from: Data(jsonString.utf8))
                        print("Object Converted: ", userData.username)
                    } catch {
                        print("Parsing Failed: ", error.localizedDescription)
                    }
                }



                break

            case .failure(let error):
                print(error)
                break
            }
        }

        return userData
    }

【问题讨论】:

  • 什么是Userjson 设置在哪里?为什么你同时使用JSONSerialization JSONDecoder
  • print("Parsing Failed: ", error.localizedDescription) => ùprint("解析失败:",错误)
  • @Larme “解析失败:No se pudo leer los datos porque no se encontraron。”
  • 然后显示获得json 的代码。编码为字符串,然后解码为 UserP 似乎是多余的 - 为什么不能简单地将获得的 JSON 数据传递给 JSONDecoder.decode()
  • 如果 nombreUsuarioempresa 不保证进入 json 那么它应该是可选的,然后你的解码器应该有类似 company = try container.decodeIfPresent(String.self, forKey: .company) 的东西

标签: json swift decode jsonresponse


【解决方案1】:

Alamofire 逻辑相关改动:

来自Alamofireresponse 有一个可以直接使用的data 属性:

let json = response.data
do {
    let user = try JSONDecoder().decode(UserP.self, from: json)
    print(user)
}
catch {
    print(error)
}

此外,如果不能保证键 nombreUsuarioempresa 出现在 json 中,那么推荐的方法是将这些变量标记为可选。有了这个,你就不需要自定义解码器逻辑了。

模型更改 #1:

struct UserP: Decodable {
    var username: String?
    var company: String?

    private enum CodingKeys: String, CodingKey{
        case username = "nombreUsuario"
        case company = "empresa"
    }
}

模型更改 #2:

如果您想提供一些默认值,那么自定义解码器可以提供帮助:

struct UserP: Decodable {
    var username: String
    var company: String

    private enum CodingKeys: String, CodingKey{
        case username = "nombreUsuario"
        case company = "empresa"
    }

    init(from decoder: Decoder) throws{
        let container = try decoder.container(keyedBy: CodingKeys.self)
        username = try container.decodeIfPresent(String.self, forKey: .username) ?? "Default Name"
        company = try container.decodeIfPresent(String.self, forKey: .company) ?? "Default Company Name"
    }
}

【讨论】:

  • 非常感谢!
  • @AntonioLabra 我很高兴 :) 注意:如果您将它们标记为可选,那么您不需要 init(from decoder: Decoder),除非您想给出明确的默认值。为了完整起见,我更新了我的答案以显示这两种情况。
  • @staticVoidMain 谈论 Alamofire 请求我该如何解决?因为它有问题并且不返回我转换的对象
  • @AntonioLabra 你得到了什么和你期待什么?
  • 我收到了我的请求,但它第一次返回“nil”。好像不是异步函数
猜你喜欢
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多