[英]Swift Codable: Array of Dictionaries
I have a JSON object from Yelp and I cannot figure out how to access the title
in categories
using Swift Codable. 我有一个来自Yelp的JSON对象,我无法弄清楚如何使用Swift Codable访问
categories
的title
。 This is the JSON (with some elements removed for ease of reading): 这是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 这是在JSON Viewer中
I access first level properties like name
easily, and I access lattitude
and longitude
like so: 我访问第一级的属性,如
name
很容易,我访问lattitude
和longitude
,像这样:
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
}
}
Could anyone please point me in the right direction towards accessing categories
-> title
? 有谁能请我指出正确的方向 - 访问
categories
- > title
? Coordinates
was easy to access but categories
is an array of dictionaries. Coordinates
很容易访问,但categories
是一系列字典。 Thank you! 谢谢!
It's the same pattern like Coordinates
except the value for categories
is an array: 这就像相同的图案
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.