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

时间:2017-07-12 07:34:33

标签: json swift xcode

大家好。我正在开发一个适用于API的应用程序。我正在努力获得"姓名"其中" Id"等于1000.当我打印名称时,它给了我一个字符串值" 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)
    }
}

2 个答案:

答案 0 :(得分:0)

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

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)
}

请尝试上面的代码段。

希望这会对你有所帮助。

答案 1 :(得分:0)

您可以尝试使用以下代码

let companyIds = ["1000", "1001"]
var companyName = [String]()
override func viewDidLoad() {
        super.viewDidLoad()
    self.apiRequestCompani { (names) in
            self.companyName = names // companyName contains all names where id == 1000
            print("companyName === \(self.companyName)")  
    }
}

func apiRequestCompani(completion: @escaping ([String]) -> ()) {
    var names = [String]()
    var resCount = 0
    for companyId in companyIds {
        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)!
        config.httpAdditionalHeaders = ["Authorization" : authString]
        let session = URLSession(configuration: config)
        let urlProjects = NSURL(string: "https://start.jamespro.nl/v4/api/json/company/"+companyId+"/?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]
                            if let items = dictionary["items"] as? AnyObject {
                                if let klantId = items["Id"] as? String, klantId == "1000" {
                                    if let name = items["Name"] as? String {
                                            print("NAME === \(name)")
                                            names.append(name)
                                    }
                                }
                            }

                        }
                        catch {
                            print("Error: Could not get any data")
                        }
                    }
                }
                resCount = resCount + 1
                if self.companyIds.count == resCount {
                    completion(names)
                }
            }

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