这是我的响应,我想使用数组打印响应我想在响应中获取一些细节,如“Id”、“可用”和“离开”,我必须在我的 VC 中的标签中显示
{
"id": 1,
"emp_id": "001",
"termination_date": "active",
"blood_group": "A+",
"rating": 0,
"noOfStars": 0,
"starOfMonth": false,
"gender": "Female",
"expertise": "",
"experience": "",
"leaves": 0,
"available": 5,
"compoff": 0,
"earnedLeaves": null,
"wfh": 0
我的代码是
struct jsonstruct8:Decodable {
var available: String
var leaves: String
var arrdata = [jsonstruct8]()
func getdata(){
let url = URL(string: "MY URL")
URLSession.shared.dataTask(with: url!) { (data, response, error )in
do{if error == nil{
self.arrdata = try JSONDecoder().decode([jsonstruct8].self, from: data!)
for mainarr in self.arrdata{
print(mainarr.available,":",mainarr.leaves)
print(data)
}
}
}catch{
print("Error in get json data")
}
}.resume()
}
我收到“获取 json 数据时出错”
最佳答案
示例 JSON:
{
"id": 1,
"emp_id": "001",
"termination_date": "active",
"blood_group": "A+",
"rating": 0,
"noOfStars": 0,
"starOfMonth": false,
"gender": "Female",
"expertise": "",
"experience": "",
"leaves": 0,
"available": 5,
"compoff": 0,
"earnedLeaves": null,
"wfh": 0
}
型号:
struct Employee: Codable {
let id: Int
let empId: String
let terminationDate: String
let available: Int
let leaves: Int
//add other properties as well....
}
解析:
if let data = data {
if let data = data {
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
var employee = try JSONDecoder().decode(Employee.self, from: data)
print("\(employee.available) : \(employee.leaves)") //here you can modify then employee details...
} catch {
print(error)
}
}
}
编辑:
始终在主线程上更新 UI。
DispatchQueue.main.async {
self.totalLeaves.text = "\(employee.leaves)"
}
关于ios - 如何使用 get 方法显示 Json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56784580/