Swift and JSON — Introducing the Codable Protocol

  • Basic types like STRING, DOUBLE, INT, DATE, DATA or URL automatically conform to Codable
  • Any type whose properties are Codable automatically conforms to Codable just by declaring conformance to the protocol:
struct Coordinate: Codable {
var latitude: Double
var longitude: Double
}
  • Built-in types such as ARRAY, DICTIONARY, and OPTIONAL also conform to Codable whenever they contain codable types
  • Indeed, any custom type can also be Codable as long as all of its properties are Codable
struct Landmark: Codable {
var name: String
var foundingYear: Int
var location: [Coordinate]
}

Encoding Swift Objects to JSON

func myEncoder<T: Encodable>(_ data: T) throws -> String {    let encoder = JSONEncoder()    encoder.keyEncodingStrategy = .convertToSnakeCase    let jsonData = try encoder.encode(data)    return String(data: jsonData, encoding: .utf8)!}

Decoding Swift Objects to JSON

  • Unless you use custom coding keys (refer to the official Apple Documentation), your property names need to match exactly to the keys supplied in the JSON string you are decoding
  • This makes sense given Swift would not know how to otherwise guess how to map JSON data to Swift Objects
  • As JavaScript is typically written in snake_case whilst Swift is written in camelCase, it is very valuable to set the keyEncodingStrategy and keyDecodingStrategy to .convertToSnakeCase (see above in myEncoder) or .convertFromSnakeCase (see below in myDecoder)
  • Any keys in the JSON string that are not defined as properties in your Swift types simply get discarded. This is helpful in that you can update your APIs on the server side without breaking the client code already installed on your users devices (and subsequently requiring an app update to fix).
func myDecoder<T: Decodable>(_ decodeType: T.Type, _ from: String) throws -> T {   let decoder = JSONDecoder()   decoder.keyDecodingStrategy = .convertFromSnakeCase   let jsonData = from.data(using: .utf8)!   return try decoder.decode(decodeType, from: jsonData)}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ashok Khanna

Ashok Khanna

Masters in Quantitative Finance. Writing Computer Science articles and notes on topics that interest me, with a tendency towards writing about Lisp & Swift