Extract Piece of JSON using Swift Codable
Codable protocol is really helpful in making developers’ life easy. It allows us to convert JSON response into the model object instead of going through the cumbersome process of parsing each object.
How do we use the Codable protocol in Swift?
To understand the concept better let’s get our hands dirty with some coding samples:
Flickr search JSON example:
Let’s go ahead and implement the codable protocol for the above JSON. Flickr feed response has a dictionary with a title, link, description, modified generator and a list of items.
Similarly, an item is a dictionary which has some properties and media dictionary as below:
Conversion of media dictionary to Swift media codable model object:
Base object FlickrSearch is a complete representation of JSON and we’ll use the base object to map JSON to Swift model:
As per the above example, we can write object mapping from JSON to Swift models and easily decode the complete JSON into the model object. What if we don’t need the complete object and require only a portion of it. Let’s say we only require the items array from the JSON response. Do you have an idea how one can achieve it?
How do we use the Codable protocol to extract part of JSON?
You might be thinking that if require only some part of JSON, then why not break the JSON into the pieces as per the requirement. Yes, it would be great if we could receive JSON responses into smaller parts. It will use a lower data bandwidth. Above solution is possible only if you are using APIs that are in-house implemented. What if you are utilizing a third-party APIs?
Do we need to write complete JSON structure using Codable protocol?
No, we can achieve this without having a complete JSON object mapping. Write mapping object for Items and Media and convert mapping list of Item as below:
As we can see in the above code, first of all, we need to convert data into a JSON dictionary and extract items list as NSArray. Convert items list into data and then again decode data into Item’s list. Originally published at Medium.