gpt4 book ai didi

arrays - 无法快速访问 JSON 中嵌套数组的数据

转载 作者:行者123 更新时间:2023-11-30 10:44:29 29 4
gpt4 key购买 nike

我有一个带有嵌套数组的 JSON,我想访问该嵌套数组中包含的数据之一,但我不知道如何做到这一点。

我正在开发一个 IOS 应用程序,并尝试从(目前是本地)JSON 中解析一些数据。我想向用户显示一些数据。

这就是我的 JSON 的样子:

{
"format": "json",
"data": [
{
"type": "channel",
"id": "789",
"updated_at": "2019-05-03 11:32:57",
"unread_count": 3,
"title": "title",
"context": "search",
"relationships": {
"recipients": [
{
"type": "user",
"rating": 5,
"is_spotlighted": false,
"id": 123,
"participant_id": 456
}
],
}
}
}

现在我通过以下方式访问不同的值:

struct Root: Decodable {
let format: String
let data: [ChannelData]
}

struct ChannelData: Decodable {
let title, type, id, context, updatedAt: String
let unreadCount: Int
let relationships: Relationships
}

struct Relationships: Decodable {
let recipients: [Recipient]
}

struct Recipient: Decodable {
let type: String
let id: Int
let participantId: Int
let isSpotlighted: Bool
let rating: Double
}

我想要访问的数据是“评级”

这就是我的 viewDidLoad() 的样子:

var chatList = [ChannelData]()

override func viewDidLoad() {

super.viewDidLoad()
let url = Bundle.main.url(forResource: "channels", withExtension: "json")!
let data = try! Data(contentsOf: url)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try! decoder.decode(Root.self, from: data)
chatList = result.data
self.tableView.reloadData()
}

当在另一个函数中时,我尝试通过以下方式访问评级:

let currentChat = chatList[indexPath.row]
cell.Name.text = currentChat.relationships.recipients

当我尝试获取 .recipients 之后的其他参数时,没有显示任何内容。我是一个使用 JSON 的初学者,或多或少也使用过 Swift。

最佳答案

Relationships 包含一个类型为 [Recipient] 的属性 recipients。您可以使用 .first 访问数组中的第一个 Recipient 对象。然后您可以从 Recipient 对象获取任何属性

cell.Name.text = currentChat.relationships.recipients.first?.rating

关于arrays - 无法快速访问 JSON 中嵌套数组的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56051200/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com