Decoding Error -- Expected to decode Dictionary<String, Any> but found an array instead
I am new to swift programming and Xcode and am try to call mysql data from the database to Xcode using Json encoding. I was able to successfully call all the data (array) but when I decide to call only one value(column) say Courses.name I get the "Decoding Error -- Expected to decode Dictionary but found an array instead." How do I work my way around this problem? My goal is to print only courses.name
import UIKit
struct Course: Decodable {
let id: String
let name: String
let member: String
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let jsonUrlString = "http://oriri.ng/aapl/service.php"
guard let url = URL(string: jsonUrlString) else
{ return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else{ return }
do {
let courses = try JSONDecoder().decode(Course.self, from: data)
print(courses.name)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}.resume()
}
}
[{"id":"1","name":"sobande_ibukun","member":"blue"}]
The []
around denotes that it is an array. Decode with the following and it should work:
let courses = try JSONDecoder().decode([Course].self, from: data)
If you are sure that it will always be one course you can do:
print(courses.first!.name)
If there may be many courses you can print every name:
courses.forEach { course in print(course.name) }