在Swift中解析json值并将ID放入var

时间:2019-06-04 08:26:24

标签: json swift

我有带ID的公司名称列表。我使用了一个下拉列表,并通过解析JSON数据在其中显示公司名称。不确定我无法在下拉菜单中获取所选项目的ID。

我的json数据是

{
"success": true,
"message": [
    {
        "company_name": "ABC",
        "id": 1
    },
    {
        "company_name": "JHG",
        "id": 10
    }
]}

我的快捷代码:

let url = NSURL(string: COMPANY_URL)
    URLSession.shared.dataTask(with: (url as?URL)!, completionHandler: {(data,response,error) ->
        Void in

        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
        {

           // print(jsonObj.value(forKey: "message")!)


            if let messageArray = jsonObj.value(forKey: "message") as? NSArray
            {
                for message in messageArray
                {
                    if let messageDict = message as? NSDictionary
                    {

                        if let data = data {


                            let successmessage = jsonObj.value(forKey: "success") as? Int

                            if(successmessage == 1)
                            {

                                if let company_name = messageDict.value(forKey: "company_name")
                                {
                                    self.companiesArray.append(company_name as! String)
                                }
                                if let company_id = messageDict.value(forKey: "id")
                                {

                                    self.companyidstr.append(company_id as! Int)

                                    print(self.companyidstr)
                                }

                                for messageArray in self.companyidstr
                                {
                                    print(messageArray)

                                    let btnlabel = Int(self.companyBtn.titleLabel!.text!)

                                    if(btnlabel == Int(messageArray))
                                    {
                                        self.companyidstring = messageArray
                                        print(self.companyidstring)
                                               // THIS IS WHERE IT NEED TO SHOW ID BUT NOT                            }
                                }



                                OperationQueue.main.addOperation({
                                    self.tableView.reloadData()
                                })




                            } else
                            {

                            }

                        }


                    }
                }
            }

        }


    }).resume()

我的要求是向用户显示公司名称的列表,但是当他们选择任何公司名称时,应以所选项目的相关ID的形式保存。

我的整个代码:

class RegistrationViewController: UIViewController, UITableViewDataSource, UITableViewDelegate  {


    @IBOutlet weak var tableView: UITableView!

    @IBOutlet weak var companyBtn: UIButton!


    final let COMPANY_URL = COMPANY_URL

    var companiesArray = [String]()

    var companyidstr = [Int]()

    var companyidstring: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        downloadCompanyNamesFromDB()
        // insertUserDetailsintoDB()
        tableView.isHidden = true
        self.downloadCompanyNamesFromDB()
        //tableView.tableFooterView = UIView()
        tableView.dataSource = self
        tableView.delegate = self
    }

    @IBAction func companyBtnClick(_ sender: Any) {
        // tableView.isHidden = false

        if(tableView.isHidden)
        {
            animate(toogle: true)

        } else
        {
            animate(toogle: false)
        }


    }

    func animate(toogle: Bool)
    {
        if(toogle)
        {
            UIView.animate(withDuration: 0.3)
            {
                self.tableView.isHidden = false
            }
        } else{
            UIView.animate(withDuration: 0.3)
            {
                self.tableView.isHidden = true
            }
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return companiesArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = companiesArray[indexPath.row] 
        print(companiesArray)
        return cell
    }        

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let companytitle = companiesArray[indexPath.row]
        companyBtn.setTitle(companytitle, for: .normal)
        print(companytitle)
       // print(companiesArray[indexPath.row].id as! String)
       // companiesArray = message   --> HERE IS THE CODE
        animate(toogle: false)
    }

    func downloadCompanyNamesFromDB()
    {    

        let url = NSURL(string: COMPANY_URL)
        URLSession.shared.dataTask(with: (url as?URL)!, completionHandler: {(data,response,error) ->
            Void in


            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
            {

                // print(jsonObj.value(forKey: "message")!)

                if let messageArray = jsonObj.value(forKey: "message") as? NSArray
                {
                    for message in messageArray
                    {
                        if let messageDict = message as? NSDictionary
                        {

                            if let data = data {                                    

                                let successmessage = jsonObj.value(forKey: "success") as? Int

                                if(successmessage == 1)
                                {


                                } else
                                {

                                }                                    
                            }
                        }
                    }
                }                   
            }
        }).resume()
    }       

    } 
}

1 个答案:

答案 0 :(得分:0)

最好

let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try! dec.decode(Root.self,from:data)
print(res.message)

// MARK: - Empty
struct Root: Codable {
    let success: Bool
    let message: [Message]
}

// MARK: - Message
struct Message: Codable {
    let companyName: String
    let id: Int
}   

var companiesArray = [Message]() 

let url = URL(string: COMPANY_URL)!
URLSession.shared.dataTask(with:url, completionHandler: {(data,response,error) ->
    Void in 
    guard let data = data else { return } 
    let dec = JSONDecoder()
    dec.keyDecodingStrategy = .convertFromSnakeCase
    let res = try! dec.decode(Root.self,from:data)
    companiesArray = res.message
    print(res.message)

    OperationQueue.main.addOperation({
        self.tableView.reloadData()
    })

}).resume()