ios - 如何使用 get 方法显示 Json 响应

标签 ios json swift get

这是我的响应,我想使用数组打印响应我想在响应中获取一些细节,如“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/

相关文章:

iphone - 如何从图像中获取单个实体?

ios - 从 Swift 中的模拟调用 super

ios - Swift UIImage 命名返回 nil 并在 Assets 中使用通用图像

ios - APNS 推送通知不适用于生产

json - polymer 子菜单/页面导航需要脚本吗?

java - 将 JSON 映射到 POJO 时出现 UnrecognizedPropertyException

javascript - 如何将 DropZone JSON 对象传递给 AngularJS?

php - 如何在 Swift 的 URLSession 请求中添加 POST 参数

swift - 在每次请求之前重新加载凭据是一种好习惯吗?

iphone - 无法设置 View Controller 的委托(delegate)