使用Realm解码嵌套非数组Object时映射失败问题求助
Hey there, let's get this decoding issue sorted out right away! The root problem here is a mismatch between your JSON structure and how you're trying to decode it:
- Your JSON has a single
kitchensobject ({ "id": 36, "name": "Sandwiches" }), but your code is trying to decode it as an array ofVendorKitchensusing[VendorKitchens].self. That's exactly why you're hitting the "Failed to map data to JSON" error.
Here's how to fix it step by step:
1. Update the VendorsList model property
Replace the List<VendorKitchens> with a single optional VendorKitchens object—since your JSON returns one kitchen entry, not a list:
class VendorsList : Object, Decodable { @objc dynamic var id : Int = 0 @objc dynamic var name : String? @objc dynamic var logo : String? // Swap List for a single object to match JSON structure @objc dynamic var kitchens: VendorKitchens? override class func primaryKey() -> String? { return "id" } private enum CodingKeys: String, CodingKey { case id case name case logo // Match the JSON key directly instead of renaming it case kitchens }
2. Fix the decoder initialization logic
Instead of trying to decode an array, decode the single VendorKitchens object. Update the init(from decoder:) method:
public required convenience init(from decoder: Decoder) throws { self.init() let container = try decoder.container(keyedBy: CodingKeys.self) self.id = try container.decode(Int.self, forKey: .id) // Use decodeIfPresent for optional string values to avoid crashes if keys are missing self.name = try container.decodeIfPresent(String.self, forKey: .name) self.logo = try container.decodeIfPresent(String.self, forKey: .logo) // Decode the single kitchens object instead of forcing it into an array self.kitchens = try container.decodeIfPresent(VendorKitchens.self, forKey: .kitchens) } }
3. Keep your VendorKitchens model as is
Your existing VendorKitchens class is already set up correctly for decoding a single object, so no changes needed here:
class VendorKitchens : Object, Decodable { @objc dynamic var id : Int = 0 @objc dynamic var name : String? override class func primaryKey() -> String? { return "id" } private enum CodingKeys: String, CodingKey { case id case name } }
Why this works:
- We've aligned the model property type (
VendorKitchens?) with the actual JSON structure (a single object instead of an array). - The decoder now correctly tries to parse a single
VendorKitchensinstance from thekitchenskey, instead of forcing it into an array which doesn't match the data.
If later your API starts returning an array of kitchens (like "kitchens": [{...}, {...}]), you can switch back to using List<VendorKitchens> and decode it as an array again. But for your current JSON, this setup will resolve the decoding error.
内容的提问来源于stack exchange,提问作者King

