Skip to content

JSONDecoder error "The given data was not valid JSON." when parsing a decimal number but expecting an Int #274

@tikitu

Description

@tikitu

The problem here is that the debug description in the error (and in its underlying error) are wildly misleading for understanding what the actual programmer mistake was.

For example decoding this JSON float value as an Int:

struct Thing: Codable {
    var value: Int
}
let json = #"{"value": 18.18}"#
do {
    let _ = try JSONDecoder().decode(Thing.self, from: Data(json.utf8))
} catch {
    print(error)
}

This produces an error claiming that the JSON is invalid and that 18.18 is not representable in Swift: as well as being wrong as stated, both are misleading for tracking down the real problem. The error as thrown on iOS 17:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], 
    debugDescription: "The given data was not valid JSON.",
    underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Number 18.18 is not representable in Swift." 
        UserInfo={NSDebugDescription=Number 18.18 is not representable in Swift.})))

Prior to iOS 17 the error reporting here did a better job steering the user to the problem. Here is iOS 15.4:

dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "value", intValue: nil)], 
    debugDescription: "Parsed JSON number <18.18> does not fit in Int.", 
    underlyingError: nil))

This seems to be where the error is thrown from:

https://github.com/apple/swift-foundation/blob/b14c22bc84b536e86e7ac70341b90dcbd8ad4229/Sources/FoundationEssentials/JSON/JSONDecoder.swift#L981

Feedback FB13211052

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions