Uploaded image for project: 'Swift'
  1. Swift
  2. SR-5249

Codable throws error when decoding an Int/Float from a JSON string

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Foundation
    • Labels:
      None

      Description

      If I have a JSON object such as

        {
          "id": "4yq6txdpfadhbaqnwp3",
          "email": "john.doe@example.com",
          "name":"John Doe",
          "spent":"1.00",
          "visits":"34"
        }
      

      with a Swift object

      struct User: Decodable {
        var id: String
        var email: String
        var name: String
        var spent: Float
        var visits: Int
      }
      

      I get the error

      typeMismatch(Swift.Float, Swift.DecodingError.Context(codingPath: [Optional(__lldb_expr_68.User.(CodingKeys in _FE7989C1DE048E5A32A5007446084784).spent)], debugDescription: "Expected to decode Float but found a string/data instead."))
      

      I would assume Codable is looking for only number types when decoding, but many of the JSON APIs I work with (e.g. Shopify) wrap their integers and prices in strings.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              itaiferber Itai Ferber
              Reporter:
              chrismanderson Chris Anderson
              Votes:
              8 Vote for this issue
              Watchers:
              14 Start watching this issue

                Dates

                Created:
                Updated: