Preface
Apple has made a lot of improvements in Swift 4.0, and my personal favorite is the emergence of the Codable protocol. It allows Swift to bring the mapping and conversion capabilities of JSON, XML structured data and Model.
The most common usage scenario of Codable is: the APP initiates a network request, and then we convert the JSON data responded to by the server into the corresponding Model entity. Because the programming specifications on the server may differ from those on the client, the Codable default data conversion implementation may no longer be applicable. For example, the server may use a serpentine naming method while the client uses a camel. At this time, we need to implement the mapping relationship on the client.
struct Mac: Codable { var name: String var screenSize: Int var cpuCount: Int } let jsonString = """ [ { "name": "MacBook Pro", "screen_size": 15, "cpu_count": 4 }, { "name": "iMac Pro", "screen_size": 27, "cpu_count": 18 } ] """ let jsonData = Data(jsonString.utf8) let decoder = JSONDecoder() do { let macs = try ([Mac].self, from: jsonData) print(macs) } catch { print() }
The appeal code does not perform the ideal decoding operation because the default implementation of Codable cannot map the serpentine variable name to the corresponding camel attribute. So in Swift 4.0 we need to partially modify our Mac:
struct Mac: Codable { var name: String var screenSize: Int var cpuCount: Int enum CodingKeys : String, CodingKey { case name case screenSize = "screen_size" case cpuCount = "cpu_count" } }
Fortunately, Swift 4.1 has made improvements to this. Now we can implement decoding operations between different programming specifications by setting the keyDecodingStrategy of JSONDecoder. Correspondingly, JSONEncoder also has a keyEncodingStrategy property for encoding operations between different programming specifications. So the appeal code can be simplified to:
struct Mac: Codable { var name: String var screenSize: Int var cpuCount: Int } let jsonString = """ [ { "name": "MacBook Pro", "screen_size": 15, "cpu_count": 4 }, { "name": "iMac Pro", "screen_size": 27, "cpu_count": 18 } ] """ let jsonData = Data(jsonString.utf8) let decoder = JSONDecoder() = .convertFromSnakeCase do { let macs = try ([Mac].self, from: jsonData) print(macs) } catch { print() }
If you want to perform reverse conversion, the code is also very simple:
let encoder = JSONEncoder() = .convertToSnakeCase let encoded = try (macs)
Of course, we can also customize the conversion strategy to achieve some specific needs. For specific usage methods, please refer to the code
Summarize
The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.