【问题标题】:How to get particular 'json' value in swift 5?如何在 swift 5 中获取特定的“json”值?
【发布时间】:2020-03-12 08:13:37
【问题描述】:

我想要 json 对象中的“成功”值,但问题是我正在获取整个 json 数据,我只想打印“成功”值

这是我的json`

{
   response = { 
                success = 1; 
                successmsg = "Successful Connection"; 
              };
}`

这是我在 swift 5 中的代码

    @IBAction func girisButtonTap(_ sender: Any) {
        var txtusername: String
        var txtpassword: String
        txtusername = usercodeText.text!
        txtpassword = passwordText.text!
        let Url = String(format: "http://10.10.10.53:8080/sahambl/rest/sahamblsrv/userlogin")
        guard let serviceUrl = URL(string: Url) else { return }
        let parameters: [String: Any] = [
            "request": [
                "xusercode" : "\(txtusername)",
                "xpassword": "\(txtpassword)"
            ]
        ]
        var request = URLRequest(url: serviceUrl)
        request.httpMethod = "POST"
        request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
        guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
            return
        }
        request.httpBody = httpBody
        request.timeoutInterval = 20
        let session = URLSession.shared
        struct ResponseJSON: Codable {
            let response: Response
        }
        struct Response: Codable {
            let success: Int
            let successmsg: String
        }
        session.dataTask(with: request) { (data, response, error) in
            if let response = response {
                print(response)
            }
            if let data = data {
                do {
                    let json = try JSONDecoder().decode(ResponseJSON.self, from: data)
                    print(json)
                    let successful = json.response.success == 1
                } catch {
                    print(error)
                }
                }
            }.resume()
    }
}

如果有任何进展,我将不胜感激。

【问题讨论】:

    标签: json swift5


    【解决方案1】:

    使用模型结构和Codable 进行解析:

    struct ResponseJSON: Codable {
        let response: Response
    }
    
    struct Response: Codable {
        // depending on what your JSON actually looks like, this could also be
        //   let success: Bool
        let success: Int
    
        let successmsg: String
    }
    
    session.dataTask(with: request) { data, response, error in
      if let response = response {
          print(response)
      }
      if let data = data {
        do {
          let json = try JSONDecoder().decode(ResponseJSON.self, from: data)
          print(json)
    
          // access the success property:
          let successful = json.response.success == 1 
          // leave off the "== 1" if it's a Bool
        } catch {
           print(error)
        }
      }
    }.resume()
    
    
    

    【讨论】:

    • 首先非常感谢您的回答。我是 Swift 软件的新手。 .......... if let data = data { do { let json = try JSONSerialization.jsonObject (with: data, options: []) print (JSON) 我需要在 print 中读取 success = 1 (json) 输出。我应该在哪里写你在我的程序中提供的代码?
    • 让成功 = json.response.success == 1 * 'Any' 类型的值没有成员 'response' 我收到错误消息。
    • 那你没有运行我的代码。我的json 的类型是ResponseJSON,而不是Any
    • 您必须去掉代码中的 JSONSerialization.jsonObject 调用,并将其替换为我向您展示的 JSONDecoder().decode(...) 调用。
    • 我做了你说的改变,但是我得到了上面程序下的输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2020-07-20
    • 1970-01-01
    相关资源
    最近更新 更多