3

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 ?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Alper
  • 1,415
  • 2
  • 13
  • 20
  • Possible duplicate of [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3) – Nazmul Hasan Jul 22 '17 at 11:35
  • Take look at my answer on how to parse a JSON response: https://stackoverflow.com/questions/42736798/how-to-parse-json-code-to-swift-3-table-view-data/42743790#42743790 – fja Jul 22 '17 at 11:49
  • use alamofire and pass dictionary any object as a json result and inner array pass as ! string as a in your aaray append item in alamofire.its should definatly better full result print json array – ronak patel Jul 22 '17 at 11:50

2 Answers2

5

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"] ?? "")
}
1

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.

ad-johnson
  • 555
  • 3
  • 17
  • Well Im known about SwiftyJSON and Alamofire but Im trying to understand the logic of parsing JSON. For example array of dictionaries, only dicitonaries, dicitonaries of dictionaries im trying to understand how to use them. – Alper Jul 22 '17 at 11:38