gpt4 book ai didi

ios - 从 HTTP JSON 树中接收特定信息

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:21:40 25 4
gpt4 key购买 nike

我如何获得它以便接收特定信息,例如“用户名”并将其放在 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)
}
...

最佳答案

你可以试试

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)

关于ios - 从 HTTP JSON 树中接收特定信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com