gpt4 book ai didi

json - Swift 中解析 json 值并获取 ID 到 var 中

转载 作者:行者123 更新时间:2023-11-30 10:42:46 25 4
gpt4 key购买 nike

我有带有 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()
}

}
}

最佳答案

最好

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

关于json - Swift 中解析 json 值并获取 ID 到 var 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56440060/

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