我不擅长为 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))
我认为这是我构造要解码的结构的方式中的一个错误,就好像我打印数据的字符串版本一样,我得到了上面显示的 JSON。
注意:我已经匿名了记录,但保留了确切的结构。
对此的任何帮助都会很棒。
谢谢
卢德斯(编辑)
最重要的规则是:
结构成员的名称必须与 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)
}