Easy JSON Parsing with Swift Codable
Internet

Easy JSON Parsing with Swift Codable

There has been a number of great libraries for parsing, but it is quite refreshing to see a fully-supported solution that is easy to adopt . Swift 4 finally answered the solution to parse JSON with new Codable protocol.

If your JSON structure and objects have similar structure, then just adopt this protocol and get useful default behavior for free. Codable is a protocol composition type, consisting of Encodable & Decodable.

Here’s an example for a User:

Let call a simple API which gives JSON data,

Now its time to parse data. Just create JSONDecoder and use decode method as given below

 And that’s it! We’ve parsed our JSON document into a User instance. It didn’t require any customization since the key names and types matched each other.

We’re using try! for the sake of an example, but in your app you should catch any errors and handle them intelligently. 

I will suggest you to watch the related WWDC session(the Codablepart starts past 23 minutes).


要查看或添加评论,请登录

Pradip Deore的更多文章

  • Swift 4 Access Levels

    Swift 4 Access Levels

    Swift 4 has the five access levels : Open you can access open classes and class members from any source file in the…

  • Map based drive simulation with X-code

    Map based drive simulation with X-code

    While developing map based iOS app solution, hit upon task which features routing navigation paths and user drive over…

  • Proper uses of Swift Extensions

    Proper uses of Swift Extensions

    Like categories in Objective-C, extensions in Swift give you the opportunity to add functionality to a type. This is…

  • iOS App Development Trends for This Year

    iOS App Development Trends for This Year

    If there is a technology or fashion, there will be a turbulence of trends. Apple, being a leader of innovations…

  • "On Contract !" Uberisation of workforce

    "On Contract !" Uberisation of workforce

    There is an increasing number of people who do not want to be employed full time. Just as people have become…

  • Searching job in IT when fresher

    Searching job in IT when fresher

    Accept reality to reach dream In future, a B Tech is not adequate to get a good job, one must have an M Tech and…

  • Becoming an efficient iOS Developer

    Becoming an efficient iOS Developer

    1. Efficient language There are a number of factors to take into account each-time we start a new mobile project…

    2 条评论

社区洞察

其他会员也浏览了