解码错误-预期对Dictionary< String,Any>进行解码但是找到了一个数组 [英] Decoding Error -- Expected to decode Dictionary<String, Any> but found an array instead
问题描述
我是快速编程和Xcode的新手,我尝试使用Json编码将mysql数据从数据库调用到Xcode.我能够成功地调用所有数据(数组),但是当我决定仅调用一个值(列)时,说Courses.name,我得到解码错误-期望对Dictionary进行解码,但是找到了一个数组".我该如何解决这个问题?我的目标是仅打印course.name
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"}]
[{"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) }
这篇关于解码错误-预期对Dictionary< String,Any>进行解码但是找到了一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!