Swift — Codable

Tram Ho

I myself am not a fan of using the third library, usually in projects I always try to write in a pure library. If you are the same person, continue reading 😜 .

To be able to parse JSON in Swift until now I know that there are two libraries that many users are SwiftyJSON and ObjectMapper but if you do not like installing via Cocoapods or Carthage then use the apple provided, that is Codable

Codable is an alias of two protocols: Decodable & Encodable , Codable protocol is used to convert JSON data object into a class or struct in Swift, this process is called Decoding because JSON data is decoded into a format that Swift understands. Codable can also encode (encoding) Swift objects into JSON.

Swift Codable basic

We will go into the first example of Swift Codable, the goal will be to convert the following JSON into Swift object (struct)

Making:

For simple JSON forms like this, just create a struct conform Codable protocol for accuracy, then use JSONDecoder () to decode the instance. Note: If no encode is needed, just conforming to the Decodable protocol is sufficient.

For array form like this

Then just add the array where the decode is

Swift Codable manual encode decode

For json like this

To handle then we do the following

Swift Codable coding key

In most cases, the client will use the json format that the server has already defined, so json types of the above format may be encountered, but if Struct can be codable, the need to define properties as person_detail, first_name. This violates the coding convention of Swift. In this case we use the Coding key to map between the properties of Struct and the key of JSON.

To decode

In case it is necessary to encode to send to the server then

It’s a bit long, but building yourself in this way is dangerous too 😂

With the above hope you will understand and feel comfortable using Codable. The first article has many shortcomings, hope everyone helps.

Source: https://nhathm.com/swift-codable-1-24d7d95584f1

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo