Crash when decoding JSON using SwiftData model with recursive relationship

This is my model:

@Model
final class Person: Codable {
    enum CodingKeys: CodingKey {
        case name
        case children
    }
    
    var name: String
    var children: [Person]?
    
    init(name: String, children: [Person]? = nil) {
        self.name = name
        self.children = children
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)
        self.children = try? container.decode([Person]?.self, forKey: .children)
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        try container.encode(children, forKey: .children)
    }
}

Note: “children” is an optional array because I will use it with List(children:) which only accepts optional arrays.

So it’s pretty simple, my model is a Person, who can have no or multiple children.

Added it to the model container:

@main
struct PersonApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .modelContainer(for: Person.self)
        }
    }
}

The JSON response I get from calling the server API:

{
    "data": [
        {
            "name": "Papa",
            "children": [
                {
                    "name": "Joe",
                    "children": null
                },
                {
                    "name": "Jane",
                    "children": [{
                        "name": "Julie",
                        "children": null
                    }]
                }]
        }
    ]
}

To decode the JSON:

let decodedData = try JSONDecoder().decode(PersonAPIModel.self, from: data)

// This is how the declaration for PersonAPIModel looks like
struct PersonAPIModel: Decodable {
    let data: [Person]
}

When I run this, I get this error:

SwiftData/BackingData.swift:386: Fatal error: Unknown related type - Person

enter image description here

What is possibly wrong?

Note: if in the JSON I replace "children": null with "children": [], I get a different error:

enter image description here

  • I don’t have access to a computer now so I can’t verify it but I am pretty sure this is a duplicate of this question

    – 

Leave a Comment