从HTTP JSON树接收特定信息

时间:2019-05-05 23:19:48

标签: ios json swift http nsurlsession

如何获取它,以便可以接收特定信息,例如“用户名”,并将其放在userName.text标签上。 (我输入的Google.com字符串只是为了简单起见。)

我一直无法找到完全适合我的问题的解决方案。谢谢!

以下是我班上的代码:

@IBOutlet weak var myData: UITextView!
    @IBOutlet weak var userName: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "https://google.com")!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"

        NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {
            (response, data, error) in

            if let data = data {
                do {

                    let json = try JSONSerialization.jsonObject(with: data, options: [])

                    print(json)
                } catch {
                    print(error)
                }
...

1 个答案:

答案 0 :(得分:0)

您可以尝试

let url = String(format: "your url")
guard let serviceUrl = URL(string: url) else { return } 
var request = URLRequest(url: serviceUrl)
request.httpMethod = "GET"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type") 
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
    if let response = response {
        print(response)
    }
    if let data = data {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String:[[String:String]]]
            let arr = json["data"]!
            print(arr.first!["username"])
            print(arr.first!["password"])
        } catch {
            print(error)
        }
    }
    }.resume()

更好

struct Root: Codable {
  let data: [Datum]
}

struct Datum: Codable {
  let username, password: String
}

使用

let json = try JSONDecoder().decode(Root.self,from: data)
print(json.data.first?.usernamae)
print(json.data.first?.password)