Swift 3 - 如何从json中提取元素?

时间:2018-03-03 20:44:16

标签: json swift3

您好我想从json中提取某些元素 代码:

var datas:[Usuario]?

    struct Usuario : Codable {
        let correo: String?
        let contrasena: String?

    }

    let urlString = "http://localhost:8080/swiftdb/logear.php"
    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if error != nil {
            print(error!.localizedDescription)
        }

        guard let data = data else { return }
        //Implement JSON decoding and parsing
        do {
            //Decode retrived data with JSONDecoder and assing type of Article object
            let articlesData = try JSONDecoder().decode([Usuario].self, from: data)
            //Get back to the main queue
            DispatchQueue.main.async {



            }

        } catch let jsonError {
            print(jsonError)
        }


        }.resume()

我想要做的是将json中的内容与文本字段进行比较,以便它可以转到不同的视图。

Json包含:

[{"correo":"unknown11@hotmail.com","contrasena":"12345"},{"correo":"lalo123@hotmail.com","contrasena":"12121"},{"correo":"kokunz@hotmail.com","contrasena":"11111"},{"correo":"a","contrasena":"a"}]

Textfield包含:{用户写入的内容.txtEmail.text Ex。}

2 个答案:

答案 0 :(得分:0)

在回答之前,您可以查看有关JSON和解析的Apple参考。 https://developer.apple.com/swift/blog/?id=37

if let dictionary = netoxJsonVariable as? [String: Any] {    
    for (key, value) in dictionary {
        // access all key / value pairs in dictionary
        // I am not sure that you can reach key with string but I think you are searching for this. 
        //if(value == "searchedMailAddress"){//then}
        //if(key == "correoLikeKey"){//then}
    }
}

答案 1 :(得分:-1)

我使用了for语句

 let {newVar} = self.{yourJson}

                for item in {newVar}! {
                    let {anotherVar} = item.{field}
                    let {anotherVar2} = item.{field2}