DEV Community

Michael Mavris
Michael Mavris

Posted on

How to parse JSON in Swift 5 (with Codable)

Parsing JSON it's a task that you will need to implement almost in every project that interacts with a REST API.

For this example, we are going to use Twitter API to get statuses class.

{
"created_at": "Wed Oct 10 20:19:24 +0000 2018",
"id": 1050118621198921728,
"id_str": "1050118621198921728",
"text": "To make room for more expression, we will now count all emojis as equal—including those with gender‍‍‍ and skin t… https://t.co/MkGjXf9aXm",
"lang": "en",
"user": {
        "id": 6253282,
        "description": "The Real Twitter API. Tweets about API changes, service issues and our Developer Platform. Don't get an answer? It's on my website.",
        "url": "https://t.co/8IkCzCDr19",
        "name":"Twitter API"
    }
}

JSONSerialisation
We have the native option which is to use the JSONSerialisation class method jsonObject(with:options:) which returns a value of type Any. Then you will most probably cast it in [String:Any] in order to access the keys and after getting the value of a specific key you should cast it again.

if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
    let user = statusesArray[0]["user"] as? [String: Any],
    let username = user["name"] as? String {
    // Finally we got the username
}

Continue reading on my personal blog

Top comments (1)

Collapse
 
jamesmalvi profile image
Jaimie Malvi

this helps and I used jsonformatter.org for json validator