Skip to content

JSONDecoder throws a broken error when parsing decimal value as Int #1604

@hiragram

Description

@hiragram

Describe the bug

JSONDecoder throws an error when the value is decimal but the expected type is Int. In the final release of Swift 5, the error represents the situation correctly, but not in Swift 6.

The behavior is slightly different between macOS and Linux.

To Reproduce

Minimal code:

import Foundation

struct Object: Decodable {
    var foo: Int
}

let json = """
{
  "foo": 123.45
}
""".data(using: .utf8)!

do {
    _ = try JSONDecoder().decode(Object.self, from: json)
} catch let error {
    print(error)
}

Result:

Target Swift Result codingPath debugDescription
Linux 6.2.1 dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: nil))
Linux 6.0 dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: nil))
Linux 5.10.1 dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "foo", intValue: nil)], debugDescription: "Parsed JSON number <123.45> does not fit in Int.", underlyingError: nil))
macOS 6.2 dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Number 123.45 is not representable in Swift." UserInfo={NSDebugDescription=Number 123.45 is not representable in Swift.})))
available in underlyingError

Expected behavior

  • codingPath should be correctly provided.
  • debugDescription should tell us what is actually happening.
  • ❓ On macOS, underlyingError provides more detailed information, but debugDescription does not, although I believe it should.

Configuration (please complete the following information):

See the table above.

Regression information:

  • On Linux:
    • Swift 5.10.1 works fine.
    • Swift 6.0 is the first broken version.
    • Swift 6.2.1 is the latest release and still broken.
  • On macOS:
    • Swift 6.2 is broken.

Additional context

Similar report about iOS/macOS: #274

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions