Read More

Swift Codable Protocol For JSON Parsing

Introduction of Swift Codable

Apple has launched the new feature in Swift to parse JSON  Swift Codable protocol. Swift 4 has introduced standard Codeable protocol which is part of the Foundation framework and JSON parsing became a single or couple of lines of code.

The Codable is a combination of two protocols, Decodable and Encodable. init(from: Decoder) and encode(to: Encoder) respectively. In other words, for a type to be “decodable” or “encodable”, they’ll need to “decode from something” and “encode to something”.

The real magic of Codable happens with the Decoder and Encoder protocols. The JSONDecoderand JSONEncoder classes use those two protocols to provide the functionality to decode/encode JSON.

Useful Points

1-> Mismatch between the strong data types of Swift and lose data types of JSON has been internally handled by the Swift compiler. We can now handle Swift Data types like Date, URL, Float, etc

2-> Using  Codable we can make the app faster. because with hel of codeable we don’t need to worried about Complex JSON and with codeable easily managed by Nesting Structure.

3-> For array JSON you don’t need to use any loop for store the data in an array object.

4-> USing Codeable we can model JSONObject or PropertyList file into equivalent Struct or Classes by writing very few lines of code

Note-> Here we will take a simple example of print the user wallet transaction details with the help of  Codeable Protocol.

Step 1-> First make the model.

Step 2-> Hit the API and get the response.

Step 3-> After Api’s response we use JSONDecoder to decode the data with our model type.

->After run the project you will get this output.

 

 

->Now you can get an index value with the help of your defined keys.

Conclusion

So pls follow the above step and And if you have any issue or suggestion you can leave your message in the comment section I will try to solve this.

 

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close