Check Mobile App
Read now

Swift Codable Protocol For JSON Parsing

Save

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.

 

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

css.php

Big thanks to Webkul and his team for helping get Opencart 3.0.3.7 release ready!

Deniel Kerr

Owner and Founder. Opencart

Talk to Sales
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home