Reading JSON from a Rails API in Swift

Caleb Hearth - Mar 4 - - Dev Community

Swift’s Codable interface allows a Swift type to be converted to and from, among other things, JSON. Besides casing disagreements which can be handled with custom CodingKey enums, converting from Rails-generated JSON to a Swift type is pretty straightforward, but one issue is that Rails’ encoding of dates is not compatible with Swift’s JSONDecoder’s default format.

Because of this, if you try to decode Rails’ created_at or updated_at columns without handling the format difference, you’ll get the error “The data couldn’t be read because it isn’t in the correct format.” with a debug description of “Date string does not match format expected by formatter.”

To avoid (or resolve) this, we can create an instance of JSONDecoder and pass a DateFormatter that uses Rails’ format for DateTime strings:

<!--

swift --> <!-- let formatter = DateFormatter() --> <!-- formatter.locale = Locale(identifier: "en_US_POSIX") //¹ --> <!-- formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" --> <!-- let decoder = JSONDecoder() --> <!-- decoder.dateDecodingStrategy = .formatted(formatter) --> <!--

-->

let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") //1 formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let decoder = JSONDecoder() decoder....
Enter fullscreen mode Exit fullscreen mode

Read More

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .