gpt4 book ai didi

arrays - swift 可编码 : Array of Dictionaries

转载 作者:搜寻专家 更新时间:2023-10-31 08:17:18 24 4
gpt4 key购买 nike

我有一个来自 Yelp 的 JSON 对象,但我不知道如何使用 Swift Codable 访问 categories 中的 title。这是 JSON(为了便于阅读删除了一些元素):

{
"businesses": [
{
"id": "fob-poke-bar-seattle-2",
"name": "FOB Poke Bar",
"is_closed": false,
"review_count": 421,
"categories": [
{
"alias": "poke",
"title": "Poke"
},
{
"alias": "salad",
"title": "Salad"
},
{
"alias": "hawaiian",
"title": "Hawaiian"
}
],
"rating": 5,
"coordinates": {
"latitude": 47.6138005187095,
"longitude": -122.343868017197
},
"price": "$$",
"location": {
"city": "Seattle",
"zip_code": "98121",
"country": "US",
"state": "WA",
"display_address": [
"220 Blanchard St",
"Seattle, WA 98121"
]
},
}

Here it is in JSON Viewer

我很容易访问一级属性,如 name,我访问 lattitudelongitude 是这样的:

class Business: Codable {

var name: String
var rating: Double
var coordinates: Coordinates

struct Coordinates: Codable {
var latitude: Double
var longitude: Double

init(lat: Double, long: Double) {
self.latitude = lat
self.longitude = long
}
}

init(name: String, rating: Double, coordinates: Coordinates) {
self.name = name
self.rating = rating
self.coordinates = coordinates
self.categories = categories
}
}

谁能给我指明访问categories -> title 的正确方向? Coordinates 很容易访问,但是 categories 是一个字典数组。谢谢!

最佳答案

它与 Coordinates 的模式相同,除了 categories 的值是一个数组:

struct Root : Decodable {
let businesses : [Business]
}

struct Business: Decodable {

let name: String
let rating: Int
let coordinates: Coordinates

let categories : [Category]

struct Coordinates: Codable {
let latitude: Double
let longitude: Double
}

struct Category: Codable {
let alias: String
let title: String
}
}

let root = try decoder.decode(Root.self, from: data)
for business in root.businesses {
for category in business.categories {
print(category.title)
}
}

关于arrays - swift 可编码 : Array of Dictionaries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48524969/

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