I am not that great at building structs for JOSN decoding yet so was hoping for some help. I have the following JSON
{
"computer": {
"location": {
"username": "john.smith",
"realname": "john smith",
"real_name": "johnsmith",
"email_address": "[email protected]",
"position": "somePosition",
"phone": "123-456-7890",
"phone_number": "123-456-7890",
"department": "",
"building": "",
"room": "someRoom01"
}
}
}
I have created the following Structs to hold it:
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
}
When I try and decode it and use it like this (part of a larger function w\ completion handler):
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)
}
I hit the catch and get this 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))
I assume this is an error in the way I have constructed the Structs to decode into as if I print a string version of the data, I get the JSON shown above.
Note: I have anonymized the record but left the exact structure intact.
Any help on this would be great.
Thanks,
Ludeth (Ed)