Easy JSON parsing with Codable

tudip-logo

Tudip

17 June 2019

Swift codable protocol has a combination of Encodable and Decodable protocol that can be used to work with JSON data in both directions. In short, Swift Codable protocol has offered the following features:

  • Using Codable, by writing very few lines of code, we can model JSONObject or PropertyList file into equivalent struct or classes. For the properties in the objects we don’t have to write the constructor. Codable hands it all. We simply need to extend our model to conform to the protocol for coding, decoding or encoding.
  • Swift compiler handled the mismatch between the strong data types of Swift and lose data types of JSON internally. We can now manage types of Swift Data such as Date, URL, Float, etc. Complex JSON can be easily modelled using readability Nesting Structs.
  • Complex JSON can be easily modelled using readability Nesting Structs.
  • Use JSONDecoder to parse actual JSON to become one-liner.

Now Let’s Get Into The Fun Part of coding

There is an API for displaying Zomato cities, and the endpoint is for Pune:

If you want to try you can try that out on link.
So, the response for this endpoint will look like this:

response-body

This is a lot of information, but we’re only going to use the following properties for the demo.

  • location_suggestions
  • status
  • id
  • name
  • country_flag_url
  • country_name

Using this simple Swift Struct, we can easily create a model for this information.

locationsuggestion-1024x275

I can probably go ahead and write a builder for every property and so on. I will stop at this stage, however, as I have already noticed the problems.

  • The constant country_flag_url is of type URL, but in JSON it is String.
  • Note also that constant is declared as a camel case that is not a standard convention for Swift.

Luckily, Codable has a response to both issues.

  • We need to make our Struct conform to the Data Type Mismatch coding protocol. It will be taken care of by the Swift compiler under the hood. We also don’t need to write the builder.
  • We can declare Coding Keys enum to solve camel case problem and tell JSON to use snake case for Swift constant and camel case.

This will look like the resulting structure:

enum-1024x517

We have now achieved snake casing for Swift and we also have Swift types in our model by complying with the Codable protocol.
Now we’ve got our JSON endpoints and model based on the JSON, let’s see how easy this JSON is to parse. First, we will apply to the endpoint and record the JSON and use JSONDecoder to parse the JSON with a single line of code.

createURL-1024x516

This is it! We’ve parsed JSON with one or several lines of code. We can now use the ZomatoCities object to print all the properties.

codable

json-response-1024x304

For more details please refer the following links:

Request a quote