DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Data
  4. Painless JSON Parsing With Swift Codable

Painless JSON Parsing With Swift Codable

In this tutorial, you'll learn how to parse JSON using Swift 4 Codable, to be able to use your data when building your mobile apps.

Shashikant Jagtap user avatar by
Shashikant Jagtap
·
Oct. 23, 17 · Tutorial
Like (1)
Save
Tweet
Share
11.35K Views

Join the DZone community and get the full member experience.

Join For Free

recently, json has become the most widely used format to transfer data all over the internet. in the world of ios development, it's very common for a developer to work with json data in swift and use it for building ios apps. there are some cool libraries like swiftyjson already available to work with json data in swift and those libraries become popular because developers don't need to deal with an unreadable mess with jsonserialization to parse json. fortunately, swift 4 has introduced amazing codable protocol as part of foundation framework and json parsing became a single or couple of lines of code. this solution is fully supported by apple and can be easily adopted. it provides customization to encode and decode complex scenarios.

in this article, we will see how to parse json using swift 4 codable by building a github information app.

at wwdc 2017, apple introduced a new feature in swift to parse json without any pain using the swift codable protocol. there is a talk available to watch on whats new in foundation , where you can watch about this new featured from the 23-minute mark onwards. basically, this protocol has a combination of encodable and decodable protocol that can be used to work with json data in both directions. in summary, swift codable protocol has offered following things to us.

  • using codable, we can model jsonobject or propertylist file into equivalent struct or classes by writing very few lines of code. we don't have to write the constructor for the properties in the objects. it's all handed by codable. we just need to extend our model to conform to the codable, decodable or encodable protocol.
  • the mismatch between the strong data types of swift and loose data types of json has been internally handled by swift compiler. we can now handle swift data types like date, url, float etc
  • complex json can be modeled easily using nesting structs for readability.
  • parsing actual json becomes a one-liner using jsondecoder .

there are many articles already written on this topic to cover the end to end introduction of codable protocol, but in this brief article, we will use the github api and build a sample app to demonstrate this feature in brief.

we will use the very famous github api to demonstrate this feature. we will build a simple app that takes a github username and shows some information when we tap the "show" button.

there is an api to display public information of github users, meaning i can find the details of my github account by using this api endpoint:

https://api.github.com/users/shashikant86

this will return the information in json format which looks like this at the moment:

{
  "login": "shashikant86",
  "id": 683799,
  "avatar_url": "https://avatars0.githubusercontent.com/u/683799?v=4",
  "gravatar_id": "",
  "url": "https://api.github.com/users/shashikant86",
  "html_url": "https://github.com/shashikant86",
  "followers_url": "https://api.github.com/users/shashikant86/followers",
  "following_url": "https://api.github.com/users/shashikant86/following{/other_user}",
  "gists_url": "https://api.github.com/users/shashikant86/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/shashikant86/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/shashikant86/subscriptions",
  "organizations_url": "https://api.github.com/users/shashikant86/orgs",
  "repos_url": "https://api.github.com/users/shashikant86/repos",
  "events_url": "https://api.github.com/users/shashikant86/events{/privacy}",
  "received_events_url": "https://api.github.com/users/shashikant86/received_events",
  "type": "user",
  "site_admin": false,
  "name": "shashikant",
  "company": "@aol, @bbc, @photobox",
  "blog": "http://shashikantjagtap.net",
  "location": "london",
  "email": null,
  "hireable": null,
  "bio": "author of bddfire & xcfit. devops automation ios swift php ruby development. ci&cd[jenkins, docker, aws, xcode server] bdd[cucumber behat cucumberish, fitnesse]",
  "public_repos": 112,
  "public_gists": 1,
  "followers": 108,
  "following": 52,
  "created_at": "2011-03-22t12:39:11z",
  "updated_at": "2017-10-05t14:32:54z"
}

this is actually a lot of information, but for the demo, we will only use the following properties:

  • name
  • avatar_url
  • location
  • followers
  • public_repos

now that we have our endpoints, let's create a single view ios application in xcode. we could use mvc, mvvm or similar pattern but we will do everything in the for this demo. we can easily model this information using simple swift struct like this:

struct mygithub {
    let name: string?
    let location: string?
    let followers: int?
    let avatar_url: url?
    let public_repo: int?
}

i can probably go ahead and write ad constructor for each property and so on. however, i will stop myself at this stage as i already spotted the problems:

  1. the constant avatar_url is of the type url , but in json, it’s string.
  2. also, notice that constant is declared as camel case, which is not swift standard convention.

fortunately, codable has an answer to both problems.

  • we have to make our struct to conform to codable protocol which will take care of data type mismatch. the swift compiler will take care of it under the hood. we don't need to write constructor as well.
  • in order to solve camel case problem, we can declare coding keys enum and tell to use snake case for swift constant and camel case for json.

the resulting struct will look like this:

struct mygithub: codable {
 
    let name: string?
    let location: string?
    let followers: int?
    let avatarurl: url?
    let repos: int?
    
    private enum codingkeys: string, codingkey {
        case name
        case location
        case followers
        case repos = "public_repos"
        case avatarurl = "avatar_url"
        
    }
}

now that, we have achieved out snake casing for swift and we also have swift types in our model by conforming to codable protocol.

parsing json with jsondecoder

now we have our json endpoints and model based on the json, let's see how easy it is to parse this json. first, we will make the request to the endpoint and grab the json, and with a single line of code, we will parse the json using jsondecoder .

guard let giturl = url(string: "https://api.github.com/users/shashikant86") else { return }
   urlsession.shared.datatask(with: giturl) { (data, response
            , error) in      
            guard let data = data else { return }
            do {
                let decoder = jsondecoder()
                let gitdata = try decoder.decode(mygithub.self, from: data)
                print(gitdata.name)
                
            } catch let err {
                print("err", err)
         }
   }.resume()

that's it! we have parsed out json with single or couple of lines of code. we can now print all the properties using the gitdata object.

preparing the ui for the app

now that we have parsed out json and we can access all the properties that needed for our app, let's build a ui for the app to ask users to enter their github username and press the "show" button. we will also put some labels to display this information in the ui.

note: i am horrible in designing the ui so my crappy storyboard looks like this.

we will then link that ui element to viewcontroller to display specific information.

source code

the source code for this demo app is available on github: decodable-swift4 .

just clone the repo and play with the code.

have fun and enjoy codable protocol. our app will look like this at the end:

using swift 4 and codable protocol, it became very easy to parse any json with any complexity and use it in an ios app. thanks to the foundation framework team for providing such a great feature embedded in swift. it's your decision to convert all your models to use codable protocol and probably retire the third-party framework that has been used to parse json from your ios apps.

Swift (programming language) JSON app Protocol (object-oriented programming) Data Types Data (computing) GitHub

Published at DZone with permission of Shashikant Jagtap, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Solving the Kubernetes Security Puzzle
  • Building Microservice in Golang
  • Spring Boot vs Eclipse MicroProfile: Resident Set Size (RSS) and Time to First Request (TFR) Comparative
  • Custom Validators in Quarkus

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: