在Swift中循环遍历JSON对象 [英] Looping through JSON object in Swift
问题描述
我得到了这个JSON对象,该对象已从服务器发送到我的Swift应用程序.
I got this JSON object which I sent from my server to my Swift application.
{
"625289": {
"id": 1,
"subject": "Hello World"
},
"625277": {
"id": 2,
"subject":"Bye World!"
}
}
因此,我尝试通过在我的Swift类中进行以下操作来获取每个结果("625289"和"625277")的主题:
So i tried to get the subject for each result ("625289" and "625277") by doing as below in my Swift class:
struct Resultat : Decodable {
let subject: String
}
var result = [Resultat]()
let urlll = URL(string:"http://localhost:8888/api/pouet.php")
URLSession.shared.dataTask(with: urlll!) { (data, response, error) in
do {
print("coucoulol")
//print(response)
self.result = try JSONDecoder().decode([Resultat].self, from: data!)
print(self.result)
for eachTicket in self.result {
print(eachTicket.subject)
}
} catch {
print("error"+error.localizedDescription)
}
}.resume()
但是,当我尝试执行代码时,它说:由于格式不正确,无法读取数据."据我了解,代码中的循环足以获取数组中的值,或者我错了.感谢您的任何帮助.
However, when I tried to execute the code, it says "The data couldn’t be read because it isn’t in the correct format." From what I understand, the loop for in the code is suffice to get the values in the arrays or maybe I'm wrong. Any help is appreciated, thanks.
推荐答案
根对象是字典.您可以将对象解码为[String:Resultat]
.该词典还包含字典.不涉及数组.
The root object is a dictionary. You can decode the object to [String:Resultat]
. The dictionary contains also dictionaries. An array is not involved.
struct Resultat : Decodable {
let subject: String
let id : Int
}
...
let result = try JSONDecoder().decode([String:Resultat].self, from: data!)
for (key, value) in result {
print(key, value.subject)
}
这篇关于在Swift中循环遍历JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!