在Swift中循环通过JSON对象
我得到了这个JSON对象,它是我从服务器发送到Swift应用程序的在Swift中循环通过JSON对象,json,swift,xcode,Json,Swift,Xcode,我得到了这个JSON对象,它是我从服务器发送到Swift应用程序的 { "625289": { "id": 1, "subject": "Hello World" }, "625277": { "id": 2, "subject":"Bye World!" } } 因此,我试图通过在Swift课堂上做以下操作来获得每个结果的主题(“625289”和“625277”): struct Resultat : Decodable { let s
{
"625289": {
"id": 1,
"subject": "Hello World"
},
"625277": {
"id": 2,
"subject":"Bye World!"
}
}
因此,我试图通过在Swift课堂上做以下操作来获得每个结果的主题(“625289”和“625277”):
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()
然而,当我试图执行代码时,它说“数据无法读取,因为它的格式不正确。”据我所知,代码中的循环足以获取数组中的值,或者可能是我错了。感谢您的帮助。根对象是字典。您可以将对象解码为
[String:Resultat]
。这本词典也包含词典。不涉及数组
struct Resultat : Decodable {
let subject: String
let id : Int
}
您可以尝试使用下面的SwiftyJSON $0.0=钥匙 $0.1=价值
let data = JSON(result)
data.dictionaryValue.forEach({
print($0.1)
})
这很奇怪……因为我已经在这里验证了这个JSON,它没有给我任何错误……仅供参考,我已经尝试在JSON中添加
[和]
,但仍然不起作用。感谢您的回复……我还有一个问题,假设我在字典中的一个键中添加了一个新变量,如“date”:“13/07/2017”
,如果另一个键没有相同的变量,如何获取Swift中的日期@瓦迪安:对不起,我不明白。所以我有一个这样的字典,其中一个键有一个变量“date”{“625289”:{“id”:1,“subject”:“Hello World”,“date”:“1/1/2018”},“625277”:{“id”:2,“subject”:“Bye World!”}
当我试图使用上面的解决方案将“date”输入我的Swift应用程序时,它显示一个错误,如“数据格式不正确”。。。这就是为什么我认为这是因为另一个键可能没有变量date..提前感谢@vadian添加可选属性:let date:String?
。您甚至可以声明let date:date?
并将适当的dateDecodingStrategy
添加到JSONDecoder
中,它工作得很好…为什么我一开始就没有想到这一点呢..再次感谢
let data = JSON(result)
data.dictionaryValue.forEach({
print($0.1)
})