Swift Codable:字典数组

时间:2018-01-30 15:27:01

标签: arrays json swift dictionary codable

我有来自Yelp的JSON对象,我无法弄清楚如何使用Swift Codable访问title中的categories。这是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 - > titleCoordinates很容易访问,但categories是一个字典数组。谢谢!

1 个答案:

答案 0 :(得分:6)

它与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)
    }
}