当特定键与SwiftyJSON匹配时,如何在JSON字典中搜索所有项目?

时间:2018-12-08 22:01:04

标签: json swift xcode

我是JSON解析世界的新手,但是我有一个JSON文件,其中包含世界上所有机场的数据,当机场ID与用户匹配时,我想获取有关机场的所有信息要求。

例如[{"id":"59","employee_name":"test","employee_salary":"0","employee_age":"0","profile_image":""},{"id":"60","employee_name":"hello","employee_salary":"123","employee_age":"23","profile_image":""},{"id":"63","employee_name":"Davron","employee_salary":"95000","employee_age":"34","profile_image":""},{"id":"66","employee_name":"Davron","employee_salary":"95000","employee_age":"34","profile_image":""},{"id":"71","employee_name":"test","employee_salary":"123","employee_age":"23","profile_image":""},{"id":"72","employee_name":"test","employee_salary":"123","employee_age":"23","profile_image":""}]

判断上面的JSON是否是我的实际JSON,并且id是59,我想要该特定ID的员工姓名,薪水,年龄和个人资料图片。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:-1)

您可以尝试

struct Root:Codable {
    let id, employeeName, employeeSalary, employeeAge,profileImage: String 
}

let decoder = JSONDecoder() 
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
     let res = try decoder.decode([Root].self,from:data)
     let con = res.filter { $0.id == "59" }
   }
catch {
 print(error)
}

OR

if let emp = res.first(where{ $0.id == "59" }) {
   print(emp)
}