Skip to content

Error decoding nested JSON with missing container #40

Description

@bzf

Hi there!

Big thanks for this package, I've really been enjoying it!

I have an issue when decoding nested JSON when one level of the keys doesn't exist.

I have this struct:

@Codable
struct Avatar {
    @CodedAt("avatar", "url")
    let url: URL?
}

Trying to decode this works fine.

func testConditionalAndNestedOptionalCodingWorking() throws {
    let jsonStr = """
        {
            "avatar": {
                "url": "https://example.com/"
             }
        }
        """
    let json = try XCTUnwrap(jsonStr.data(using: .utf8))
    let model = try JSONDecoder().decode(Avatar.self, from: json)
    XCTAssertEqual(model.url, URL(string: "https://example.com/"))
}

Decoding JSON with a value for "url" also works.

func testConditionalAndNestedOptionalCoding() throws {
    let jsonStr = """
        {
            "avatar": {
                "url": null
             }
        }
        """
    let json = try XCTUnwrap(jsonStr.data(using: .utf8))
    let model = try JSONDecoder().decode(Avatar.self, from: json)
    XCTAssertEqual(model.url, nil)
}

The problem is when the "avatar" value is null.

func testMissingContainer() throws {
    let jsonStr = """
        {
            "avatar": null
        }
        """
    let json = try XCTUnwrap(jsonStr.data(using: .utf8))
    let model = try JSONDecoder().decode(Avatar.self, from: json)
    XCTAssertEqual(model.url, nil)
}

Since my struct has an optional type for the url property, I would expect it to ignore the missing container and fallback to setting the value as nil. Instead, I get back an error:

typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found a null value instead.", underlyingError: nil))

I tried setting a default value using @Default(nil as URL?) but that didn't seem to work.

Anything I'm missing here or is this a bug?

Thanks again for the package!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinggood first issueGood for newcomers

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions