Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON Array of Dictionaries

Tags:

json

ios

swift

I am a newbie to parsing JSON and using Restful API. Whatevs, i have been looking a lot for this issue and I found lots of. But I couldn't figure it out.

JSON that I want to parse is: http://jsonplaceholder.typicode.com/users

guard let url = URL(string: "http://jsonplaceholder.typicode.com/users/") else {return}
    let session = URLSession.shared

    session.dataTask(with: url) { (data, response, error) in
        if error != nil {
            print(error ?? "")
        }
        if data != nil {
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves)

                guard let idk = json as? [Dictionary<String, Any>] else {return}

               print(idk)
            }
            catch{
                print(error)
            }
        }
    }.resume()

I came untill here and I can't move on. For example I'd like to reach id, name and username but I dont know what to do anymore. And Im wonder what if I'd like to dive into the dictionary of Adress ?

like image 237
Alper Avatar asked Jan 22 '26 02:01

Alper


2 Answers

This is an example how you can read the data:

for data: Dictionary<String, Any> in idk{
        if let address = data["address"] as? Dictionary<String, Any>{
                //here the data in address: { .. } is available
                //for example
                print(address["city"] ?? "")
        }

        //or id
        print(data["id"] ?? "")

        //username
        print(data["username"] ?? "")
}
like image 160
Vasil Hristov Avatar answered Jan 23 '26 15:01

Vasil Hristov


Alper, why don't you use SwiftyJSON to do this. Download the cocoa pod and follow instructions on their Github page: https://github.com/SwiftyJSON/SwiftyJSON

Parsing then becomes very simple. It would appear that in Swift 4, JSON is handled much better and libraries like SwiftyJSON won't be required.

like image 34
ad-johnson Avatar answered Jan 23 '26 17:01

ad-johnson