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
}
Top comments (1)
this helps and I used jsonformatter.org for json validator