swift-corelibs-foundation: [SR-5249] Codable throws error when decoding an Int/Float from a JSON string

Previous ID SR-5249
Radar rdar://problem/32850823
Original Reporter chrismanderson (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 9
Component/s Foundation
Labels Bug
Assignee @itaiferber
Priority Medium

md5: 3573648798d9e727b67a246b3e28a7f1

relates to:

  • SR-5278 JSON number should be decodable/encodable to Decimal value in Swift 4 encoding/decoding

Issue 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.

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Comments: 26 (24 by maintainers)

Most upvoted comments

Comment by Chris Anderson (JIRA)

@itaiferber that’s not a bad suggestion but it’s still not ideal to have to deal with a wrapper struct. It’s also tricky for JSON values that can be both strings and ints (it happens 🙁). With the structure of Codable as is, there’s a lot of manual work which (sort of) negates the benefit of Codable in the first place.

Has there been any thought to allowing a user to custom decode one attribute but let Codable handle all the others? Or, allow a user to write their own decoding strategies ala https://developer.apple.com/documentation/foundation/jsonencoder/2895199-nonconformingfloatencodingstrate?