解码错误 -- 预期解码 Dictionary<String, Any>但找到了一个数组 [英] Decoding Error -- Expected to decode Dictionary<String, Any> but found an array instead
问题描述
我是 Swift 编程和 Xcode 的新手,我尝试使用 Json 编码将数据库中的 mysql 数据调用到 Xcode.我能够成功调用所有数据(数组),但是当我决定只调用一个值(列)说 Courses.name 时,我收到解码错误 - 预期解码字典但找到了一个数组".我如何解决这个问题?我的目标是只打印courses.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屋!