我在使用 Swift 4 解码功能解码 JSON 响应时遇到问题。我有主结构,它有一个内部结构 var hr_employees: [Employee]? = []。问题是 JSON 没有映射 'var hr_employees: [Employee]?= []。
我得到了三个根值 response_status、access_level、session_token 的正确值。
///////////结构代码/////////////////////
struct EmployeeData: Codable {
var response_status:Int=0
var access_level:Int=0
var session_token:String=""
var hr_employees: [Employee]? = []
}
private enum CodingKeys: String, CodingKey {
case response_status="response_status"
case access_level="access_level"
case session_token="session_token"
case hr_employees="hr_employees"
}
init() {
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
response_status = try values.decode(Int.self, forKey: .response_status)
do{
session_token = try values.decode(String.self, forKey: .session_token)
}catch {
print( "No value associated with key title (\"session_token\").")
}
do{
access_level = try values.decode(Int.self, forKey: .access_level)
}
catch {
print( "No value associated with key access_level ")
}
}
///////////////内部结构///////////////////
struct Employee: Codable {
var userId:Int=0
var nameFirst:String=""
var nameLast:String=""
var position:String=""
var company:String=""
var supervisor:String=""
var assistant:String=""
var phone:String=""
var email:String=""
var address:String=""
var gender:String=""
var age:Int=0
var nationality:String=""
var firstLanguage:String=""
var inFieldOfView:String = "0"
var photo:String="user-default"
var status:String="3"
}
///////////下面是JSON///////////////////
{
"response_status":1
,"access_level":2
,"hr_employees":[
{
"user_id":4226
,"name_last":"Sampe"
,"name_first":"Frederica"
,"position":"Systems Maint"
,"phone":"123456"
,"email":"omega@demo.mobile"
,"address":"00100 Helsinki 1"
,"age":67
,"company":"Omega Enterprise"
}
,{
"user_id":5656
,"name_last":"Aalto"
,"name_first":"Antero"
,"position":"Programming Methodology and Languages Researcher"
,"supervisor":"Mayo Georgia"
,"phone":"123456"
,"email":"omega@demo.mobile"
,"address":"00100 Finland "
,"age":51
,"company":"Omega Fire Related Equipment"
}
]
}