在Swift中循环遍历JSON对象

编程入门 行业动态 更新时间:2024-10-10 14:28:02
本文介绍了在Swift中循环遍历JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我得到了这个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:"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对象

本文发布于:2023-11-26 09:00:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633467.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   对象   Swift   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!