【问题标题】:Swift read from JSON dictionarySwift 从 JSON 字典中读取
【发布时间】:2023-02-04 04:24:58
【问题描述】:

我正在发送一个 Alamofire 请求,在我的完成处理程序中我有:

                if let jsonData = response.result.value {
                    
                    result = jsonData
                    guard let data = result.data(using: .utf8) else { return}
                    guard let dictionary = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
                                        print("Could not cast JSON content as a Dictionary<String, Any>")
                                        return
                                    }
                            
                    print("dictionary: \(dictionary)")
                    if dictionary["status"] as! String == "false"{
                         //Do something
                                 }
                    }
            

                else{
                    result = "\(response.error)"
                    
                }

打印dictionary的结果是["status":false, "value":A1]。最终我想在我的 if 语句中使用 status。但是,我在 if 语句行发生崩溃:if dictionary["status"] as! String == "false" of Fatal error: Unexpectedly found nil while unwrapping an Optional value。我还尝试将行更改为 if dictionary["status"] as! Bool == false,但我得到了完全相同的错误。

从请求返回的 json 是:

{
    "value": "A1",
    "status": "false"
}

所以我的问题是,从dictionary 中获取status 的值的正确方法是什么?

这样的事情行得通吗?

struct jsonOut: Codable {
  let value: String
  let status: String
}

if let jsonData = response.result.value {

                    result = jsonData
                    guard let data = result.data(using: .utf8)
                    let status = try JSONDecoder().decode(jsonOut.self, from: data)

}

【问题讨论】:

  • 您需要显示初始 JSON。你有什么理由不使用Codable
  • 使用 json 更新问题并尝试Codable。我想我需要一些指导
  • 您是否尝试过 Codable 代码,它对我来说看起来不错?
  • 然后请删除问题或发布您的解决方案作为答案
  • 旁注,怀疑你用的是Alamofire,所以直接用.responseDecodabel(of:)

标签: json swift alamofire


【解决方案1】:

由于 JSON 具有以下格式:

{
"value": "A1",
"status": "false"
}

正确的方法是使用与 JSON 格式相同的 Codable

struct jsonOut: Codable {
  let value: String
  let status: String
}

if let jsonData = response.result.value {

                    result = jsonData
                    guard let data = result.data(using: .utf8)
                    let statusData = try JSONDecoder().decode(jsonOut.self, from: data)

                    print("status: (statusData.status)"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多