Swift JSON decoding error: Key not found for “id” in custom type AnimalGroup

I’m encountering a fatal error when trying to decode a JSON file into my custom Swift struct AnimalGroup. The error occurs when decoding the file classification.json, and it specifically complains about a missing “id” key even though the “id” key is present in the JSON.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Fatal error: Couldn't parse classification.json as AnimalGroup:
keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))
</code>
<code>Fatal error: Couldn't parse classification.json as AnimalGroup: keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil)) </code>
Fatal error: Couldn't parse classification.json as AnimalGroup:
keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))

Here is my AnimalGroup struct:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>struct AnimalGroup: Identifiable, Decodable, Hashable {
let id: Int
let code: Int
let form: String?
let name: String
let shortName: String
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(name)
}
}
</code>
<code>struct AnimalGroup: Identifiable, Decodable, Hashable { let id: Int let code: Int let form: String? let name: String let shortName: String func hash(into hasher: inout Hasher) { hasher.combine(id) hasher.combine(name) } } </code>
struct AnimalGroup: Identifiable, Decodable, Hashable {
    let id: Int
    let code: Int
    let form: String?
    
    let name: String
    let shortName: String
    
    func hash(into hasher: inout Hasher) {
            hasher.combine(id)
            hasher.combine(name)
        }
}

This is how I load JSON data and return the decoded data:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var previewAnimal: Animal = load("animal.json")
var previewGroup: AnimalGroup = load("classification.json")
// Function that loads JSON data into a T type and returns the decoded data
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find (filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load (filename) from main bundle:n(error)")
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase // Remember to add this line to avoid running into a crash
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse (filename) as (T.self):n(error)")
}
}
</code>
<code>var previewAnimal: Animal = load("animal.json") var previewGroup: AnimalGroup = load("classification.json") // Function that loads JSON data into a T type and returns the decoded data func load<T: Decodable>(_ filename: String) -> T { let data: Data guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else { fatalError("Couldn't find (filename) in main bundle.") } do { data = try Data(contentsOf: file) } catch { fatalError("Couldn't load (filename) from main bundle:n(error)") } do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase // Remember to add this line to avoid running into a crash return try decoder.decode(T.self, from: data) } catch { fatalError("Couldn't parse (filename) as (T.self):n(error)") } } </code>
var previewAnimal: Animal = load("animal.json")
var previewGroup: AnimalGroup = load("classification.json")


// Function that loads JSON data into a T type and returns the decoded data
func load<T: Decodable>(_ filename: String) -> T {
    let data: Data

    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            fatalError("Couldn't find (filename) in main bundle.")
    }

    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load (filename) from main bundle:n(error)")
    }

    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase // Remember to add this line to avoid running into a crash
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse (filename) as (T.self):n(error)")
    }
}

Here is a sample of my classification.json file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"group": [
{
"code": 3,
"form": null,
"id": 1,
"name": "Vertebrates",
"short_name": "CRS",
},
{
"code": 4,
"form": null,
"id": 2,
"name": "Mammal",
"short_name": "CRS",
},
{
"code": 5,
"form": null,
"id": 3,
"name": "Reptile",
"short_name": "CRS",
},
{
"code": 6,
"form": null,
"id": 4,
"name": "Avians",
"short_name": "CRS",
},
{
"code": 7,
"form": null,
"id": 5,
"name": "Amphibians",
"short_name": "CRS",
}
]
}
</code>
<code>{ "group": [ { "code": 3, "form": null, "id": 1, "name": "Vertebrates", "short_name": "CRS", }, { "code": 4, "form": null, "id": 2, "name": "Mammal", "short_name": "CRS", }, { "code": 5, "form": null, "id": 3, "name": "Reptile", "short_name": "CRS", }, { "code": 6, "form": null, "id": 4, "name": "Avians", "short_name": "CRS", }, { "code": 7, "form": null, "id": 5, "name": "Amphibians", "short_name": "CRS", } ] } </code>
{
    "group": [
        {
            "code": 3,
            "form": null,
            "id": 1,
            
            "name": "Vertebrates",
            "short_name": "CRS",
            
        },
        {
            "code": 4,
            "form": null,
            "id": 2,
            
            "name": "Mammal",
            "short_name": "CRS",
            
        },
        {
            "code": 5,
            "form": null,
            "id": 3,
            
            "name": "Reptile",
            "short_name": "CRS",
            
        },
        {
            "code": 6,
            "form": null,
            "id": 4,
            
            "name": "Avians",
            "short_name": "CRS",
            
        },
        {
            "code": 7,
            "form": null,
            "id": 5,
            
            "name": "Amphibians",
            "short_name": "CRS",
            
        }
        
    ]
}

My question:
How can I handle the situation where a key like “id” is not missing from the JSON but Xcode is saying it’s missing?

I used the Decodable protocol to decode my JSON into the AnimalGroup struct. The JSON includes the id field, so I expected the decoding to work. However, despite the id being present in the JSON, I’m still getting the keyNotFound error during decoding.

I was expecting the decoder to map the id key from the JSON to the AnimalGroup struct without any issues, but it results in a fatal error instead.

Your struct handles the fields of a single animal. Your JSON contains a dictionary with the key “group”. The value for that key is an array of your AnimalGroup structs.

You need an outer object that hosts an array of AnimalGroup objects (“AnimalGroupGroup”?)

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật