Parse JSON Without Knowing the Type: iOS Swift

A lifesaver!

Image for post
Image for post
Photo by Pankaj Patel on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 11.6, and Swift 5.2.4

You’d usually be well advised to use Postman to understand what type of data you are going to download from an EndPoint, or even better use your API documentation (or have a chat with your neighbourhood friendly backend developer).

But what if there is a problem, and you want a quick and dirty solution to seeing the response from the EndPoint right in the App.

That is the problem that this article seeks to solve.

Prerequisites:

Terminology

Endpoint: An endpoint is a remote computing device that communicates back and forth with a network to which it is connected

JSON: JavaScript Object Notation, a lightweight format for storing and transporting data

The code

The main code for this is rather short. You can perform the following when you have received data from an endpoint, and then while writing your code (you wouldn’t do this in production, right? You’d know the model…even…you’d…)

The code in situ

The project is in the repo which of course features one of those rather large issues — calling a network service from a UIViewController class and I’d usually recommend anyone use MVVM-C or similar, this is just an example and gives access to full testing for the network manager etc.

So a larger example (here in the viewDidLoad() method) and calls https://jsonplaceholder.typicode.com/todos/8 which is an endpoint that can be called using the following code:

Conclusion

Knowing the type of data that you will receive from an endpoint is really important. You might feel that you’d always need Postman to solve this type of problem. However, there are instances where you are downloading JSON and it seems to work in Postman but not in your iOS implementation — what might be going wrong?

This article has hopefully given you a solution to this problem.

If you’ve any questions, comments or suggestions please hit me up on Twitter]

Why not sign up to my newsletter

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