I'm trying to parse JSON from the seat geek API but I keep getting a JSON error. I have tried rearranging the structs but to no avail.
This is what I have now but it is not working. Please help.
import Foundation
class Concerts {
struct Returned: Codable {
let events: [EventsData]
}
struct EventsData: Codable {
var url: String
var type: String
var venue: Location
var performers: [Performer]
}
struct Performer: Codable {
var name: String
}
struct Location: Codable {
var display_location: String!
var name: String
}
var url = "https://api.seatgeek.com/2/events?venue.state=NY?client_id=\(APIkeys.seatGeekKey)"
var concertArray: [ConcertData] = []
var count = 0
func getData(completed: @escaping () -> ()) {
let urlString = url
guard let url = URL(string: urlString) else {
completed()
return
}
let session = URLSession.shared
let task = session.dataTask(with: url) { data, response, error in
if error != nil {
print("ERROR")
}
do {
let returned = try JSONDecoder().decode(Returned.self, from: data!)
for data in returned.events {
self.concertArray.append(ConcertData(venue: data.venue.name, name: data.performers.first?.name ?? "", location: data.venue.display_location, type: data.type, url: data.url ?? ""))
}
} catch {
print("JSON Error")
}
completed()
}
task.resume()
}
}
CodePudding user response:
Try the Alamofire and SwiftyJSON. The method for fetching data with json reader got deprecated.
struct DataItem: Decodable{
let param1: String?
let param2: String?
let param3: SubDataItem?
enum CodingKeys: String, CodingKey{
case param1 = "param1_key"
case param2 = "param2_key"
case param3 = "param3_key"
}
}
struct SubDataItem: Decodable{
let abc: String?
enum CodingKeys: String, CodingKey{
case abc = "abc"
}
}
struct DataList: Decodable{
let results: [DataItem]?
enum CodingKeys: String, CodingKey{
case results = "results"
}
}
func loadData(parameter){
let url = "url"
let parameters: [String: Any] = [
"xyz": value
]
AF.request(url, parameters: parameters)
.validate()
.responseDecodable(of: DataList.self) { response in
guard let dataList = response.value else {
print("failed")
return
}
print(dataList.results?.count ?? 0)
}
}
CodePudding user response:
Identified the problem from the comment of @workingdogsupportUkraine
Your API endpoint is not in the correct format, you need to replace ?
with &
before client_id
of your URL.
var url = "https://api.seatgeek.com/2/events?venue.state=NY&client_id=\(APIkeys.seatGeekKey)"