簡體   English   中英

如何在swift 5中獲得特定的“json”值?

[英]How to get particular 'json' value in swift 5?

我想要 json 對象中的 'success' 值,但問題是我正在獲取整個 json 數據我只想打印 'success' 值

這是我的 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()
    }
}

如有任何進展,我將不勝感激。

使用模型結構和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()


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM