0

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)

1 Answer 1

3

The most significant rule is:

The name of the struct member must match the JSON key unless you map keys with CodingKeys

To conform to the naming convention I added the snake_case conversion

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)
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Vadian has the answer here. This is also great info for me! I had no idea about the name matching. The SnakeCase is also a great tip. Marked as answered. Thanks a lot for taking the time to share your expertise. This site has helped me learn stuff like this that I did not pick up from a book or just learn on my own lol.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.