我不是很擅长为JOSN解码构建结构,因此希望能有所帮助。我有以下JSON
{
"computer": {
"location": {
"username": "john.smith",
"realname": "john smith",
"real_name": "johnsmith",
"email_address": "johnsmith@company.com",
"position": "somePosition",
"phone": "123-456-7890",
"phone_number": "123-456-7890",
"department": "",
"building": "",
"room": "someRoom01"
}
}
}
我创建了以下结构来保存它:
struct ComputerRecord: Codable {
public let locationRecord: Location
}
struct Location: Codable {
public let record: Record
}
struct Record: Codable {
public let username: String
public let realname: String
public let real_name: String
public let email_address: String
public let position: String
public let phone: String
public let phone_number: String
public let department: String
public let building: String
public let room: String
}
当我尝试对其进行解码并像这样使用它(带有完成处理程序的较大功能的一部分)时:
do {
let decoder = JSONDecoder()
let computer = try decoder.decode(jssComputerRecord.self, from: data)
if computer.locationRecord.record.username == nameToCheck {
usernameSet(true, response, error)
} else {
print("In the else")
usernameSet(false, response, error)
}
} catch {
print(error)
usernameSet(false, response, error)
}
我抓住了这个错误:
keyNotFound(CodingKeys(stringValue: "locationRecord", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"locationRecord\", intValue: nil) (\"locationRecord\").", underlyingError: nil))
我认为这是我构造Structs进行解码的方式时出现的错误,就像打印数据的字符串版本一样,我得到了上面显示的JSON。
注意:我已将记录匿名化,但保留了完整的结构。
任何对此的帮助都会很棒。
谢谢
Ludeth(Ed)
答案 0 :(得分:2)
最重要的规则是:
结构成员的名称必须与JSON密钥匹配,除非您使用CodingKeys
为了符合命名约定,我添加了 snake_case 转换
struct ComputerRecord: Codable {
public let computer: Computer
}
struct Computer: Codable {
public let location: Record
}
struct Record: Codable {
public let username: String
public let realname: String
public let realName: String
public let emailAddress: String
public let position: String
public let phone: String
public let phoneNumber: String
public let department: String
public let building: String
public let room: String
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(ComputerRecord.self, from: data)
if result.computer.location.username == nameToCheck {
usernameSet(true, response, error)
} else {
print("In the else")
usernameSet(false, response, error)
}
} catch {
print(error)
usernameSet(false, response, error)
}