从 API 解码 JSON - Swift 5

Decoding JSON From API - Swift 5

我不太擅长为 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。

注意:我已将记录匿名化,但完整保留了确切的结构。

任何帮助都将非常有用。

谢谢,

Ludeth(编)

最重要的规则是:

结构成员的名称必须与 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)
  }