JSON (De)Serialization in Swift
Now that I have got my Node.js server up and running I have moved on to working on the client side of the application. The first task I had to tackle was making API calls and handling JSON responses. In this post I’ll walk you through the code to accomplish this task. The first step is creating classes that are JSONifiable.
Thankfully, a lot of the functionality comes pre-built into swift. Here I will be using JSONEncoder and JSONDecoder to handle the serialization and deserialization of objects. I added two functions to encapsulate this, encode() which turns an object into JSON data that can be transmitted to the server and decode() which takes data and turns it into a Swift object. You can see an example below for how this can be used.
The next part is using this Transmittable protocol to make API calls to the server with JSON body and receiving and handling response data.
The main function of this APICaller class is to perfom an API call to an endpoint on the server. This function takes an endpoint (“/users”), a method (“POST”), a request body (a User object), and the response type (User.self). It calls createURLRequest() to format a URLRequest object. It then uses URLSession to make the call to the backend. Next, we check the HTTP response code. Any code other than 200 (or something in the 200s) means the call traversed the network successfully, but that there was an error that the server raised. If all the checks pass, we deserialize the data returned by the server and call the completion handler.
In the example above, we make a POST call to the /users endpoint with User object body. In this case, we also return a User object in the response from the server.
Hope this helps you with your project. Questions, comments, and corrections are always welcome.