0

This is json code:

{
  "status":"success",
   "data":
     [
       {"id":"3",
        "city_name":"Delhi",
         "city_image":"delhi.png"},
       {"id":"4",
        "city_name":"Mumbai",
        "city_image":"tickmark.png"}
     ]
 }

My Swift Code :

struct city: Decodable{
    let status : String
    let id: String
    let data : String
    let city_name: String
    let city_image: String
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonUrl = "http://parking.onlinekiduniya.org/api/cityList.php"
        let url = URL(string: jsonUrl)
        URLSession.shared.dataTask(with: url!) {(data, response, error) in
            do {
                let cities = try JSONDecoder().decode([city].self, from: data!)
                for city in cities {
                print(city.id)
            }
            }
            catch {
                print("we got error")
        }
        }.resume()
    }
}

1 Answer 1

1

Replace

let cities = try JSONDecoder().decode([city].self, from: data!)

with

let root = try JSONDecoder().decode(Root.self, from: data!)
let cities = root.data
cities.forEach {
   print($0.id)
}

struct Root: Codable {
    let status: String
    let data: [City]
}

struct City: Codable {
    let id, cityName, cityImage: String // you can use snake case also

    enum CodingKeys: String, CodingKey {
        case id
        case cityName = "city_name"
        case cityImage = "city_image"
    }
}

Your root is a dictionary not an array

Sign up to request clarification or add additional context in comments.

6 Comments

Ok thanks for your quick response. I replaces this line of code but now I am getting error . -----Variable used within its own initial value
@VidurBahl follow the whole answer content
Ok what should be print line for printing my data .? Thanks @sh_khan
Thanks a lot bro you saved my day :) Very much appreciate your fast and accurate response. Also which is the good way to learn json Integration in swift. ? Thanks once again
@VidurBahl first you should learn how to structure the json correctly with jsonlint.com then generate swift files with app.quicktype.io
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.