gpt4 book ai didi

json - 如何在 Swift 中获取行等于变量的 JSON 对象

转载 作者:行者123 更新时间:2023-11-30 12:18:50 25 4
gpt4 key购买 nike

大家好。我正在开发一个可与 API 配合使用的应用程序。我试图获取“Id”等于 1000 的“Name”。当我打印“Name”时,它会给出一个字符串值“Todd”。谁能帮我 ?这是我的 JSON 响应。

enter image description here

这是我的代码。

func apiRequestCompani(){
for index in companyId {
let config = URLSessionConfiguration.default
let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
let password = "G23@rE9t1#"
let loginString = String(format: "%@:%@", username, password)
let userPasswordData = loginString.data(using: String.Encoding.utf8)
let base64EncodedCredential = userPasswordData?.base64EncodedString()
let authString = "Basic " + (base64EncodedCredential)!
print(authString)
config.httpAdditionalHeaders = ["Authorization" : authString]
let session = URLSession(configuration: config)

let urlProjects = NSURL(string: "https://start.jamespro.nl/v4/api/json/company/"+index+"/?limit=10")
let task = session.dataTask(with: urlProjects! as URL) {
( data, response, error) in
if let taskHeader = response as? HTTPURLResponse {
print(taskHeader.statusCode)
}
if error != nil {
print("There is an error!!!")
print(error)
} else {
if let content = data {
do {
let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
print(dictionary)

if let items = dictionary["items"] as? AnyObject {
if let klantId = items["Id"] as? String {
if klantId == "1000" {
//print(klantId)
}
}


if let name = items["Name"] as? String {
self.companyName.append(name)
//print(self.companyName)
}
}

}
catch {
print("Error: Could not get any data")
}
}
}
}

task.resume()
//print( urlProjects)
}
}

最佳答案

我认为你可以做这样的事情

var dict: [AnyHashable: Any]? = (response.responseDict()["items"] as? [AnyHashable: Any])
if (dict?.value(forKey: "BranchId") == "1000") {
var name: String? = (dict?.value(forKey: "Name") as? String)
}

请尝试上面的代码片段。

希望这对您有帮助。

关于json - 如何在 Swift 中获取行等于变量的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45051226/

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