-
-
Notifications
You must be signed in to change notification settings - Fork 39
Closed
Labels
bugSomething isn't workingSomething isn't workinggood first issueGood for newcomersGood for newcomers
Description
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!
soumyamahunt
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't workinggood first issueGood for newcomersGood for newcomers