这是我的响应,我想使用数组打印响应,我想在响应中获取一些详细信息,例如“ Id”,“ available”和“ leaves”,并且必须在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数据时出错”
答案 0 :(得分:1)
示例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)"
}