转换JSON嵌套对象

时间:2016-10-27 18:03:21

标签: ios json swift3 foursquare swifty-json

我从Foursquare API获得以下JSON,我一直在努力提取数据:

{
  "meta":{
    "code":200,
    "requestId":"58122e59498e5506a1b23580"
  },
  "response":{
    "venues":[
      {
        "id":"4d56c381a747b60cd4a12c2b",
        "name":"Sports Circle",
        "contact":{},
        "location":{
          "lat":31.9,
          "lng":35.9,
          "labeledLatLngs":[
            {
              "label":"display",
              "lat":31.9,
              "lng":35.90
            }
          ],
      ],
      "confident":true
    }
  }
}

除了namevenues值之外,我想在lat中获得lng。到目前为止我已经尝试了这个,但是它在JVenues处的第二个if语句中出来了,因为它是nil

func parseData (JSONData: Data){
    do {
        var readableJson = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! [String:AnyObject]

        if let JResponse = readableJson ["response"] as? [String:AnyObject] {
            if let JVenues = JResponse["venues"] as? [String:AnyObject]{
                if let JName = JVenues["name"] as? String{
                    NSLog(JName)
                }
            }
        }
    } catch {
        print(error)
    }
}

1 个答案:

答案 0 :(得分:2)

这是其他答案所得到的。如果你能看到它全部布局,那可能会更有意义......

if let JResponse = readableJson ["response"] as? [String : AnyObject] {
    if let JVenues = JResponse["venues"] as? [[String : AnyObject]] {
        if let JName = JVenues.first?["name"] as? String {
            NSLog(JName)
        }
    }
}

请注意,这只会在场地数组中获得FIRST名称。

编辑:

我更喜欢这样的东西。定义结构并将字典转换为结构:

struct Venue {
    var name: String?
    var venueId: String?

    init(_ venueDictionary: [String : AnyObject]) {
        self.name = venueDictionary["name"] as? String
        self.venueId = venueDictionary["id"] as? String
    }
}

在你的班级中创建一个属性,例如:

var venues = [Venue]()

从您的JSON地图中将词典添加到场地阵列。我重命名了以约会资本开头的变量。

if let response = readableJson ["response"] as? [String : AnyObject] {
     if let responseVenues = response["venues"] as? [[String : AnyObject]] {
         self.venues = responseVenues.map({ Venue($0)) })
     }
 }

在班级的任何地方使用,例如:

let venue = self.venues.first
print(venue?.name)

或者:

if let venue = self.venues.find({ $0.name == "Sports Circle" }) {
    print("found venue with id \(venue.venueId)")
}