iOS swift将JSON分离为数组

时间:2016-10-27 13:50:54

标签: ios arrays json swift swifty-json

我有一个JSON这样的文件:

{
"timeline": {
"Milan": {
  "placeA": [
    {
      "name": "Place 1",
      "kind": "historic",
    },
    {
      "name": "Place 2",
      "kind": "historic",
    },
    {
      "name": "Place 3",
      "kind": "historic",
    }
  ]
},
"Paris": {
  "placeB": [
    {
      "name": "Place 1",
      "kind": "historic",
    },
    {
      "name": "Place 2",
      "kind": "historic",
    }
  ]
}
}
}

并且在我的应用中,我需要将此JSON分开并插入到这样的数组中,以便使用tableView部分显示单独的数据:

var arr = [[placeA],[placeB],...]

我该怎么做?

P.S我使用SwiftyJson

1 个答案:

答案 0 :(得分:1)

 struct City {

let name : String
let kind : String

}

var cities = [City]()

  let path = (try? Data(contentsOf: URL(string: "http://www.yourwebsite.json")!)) as Data!
    // let jsonData = NSData(contentsOfFile: path) as NSData!
    var error : NSError?
    let ReadableJSON2 = JSON ( data:path!, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil )
    print(error)

    do {
        let jsonObject = try JSONSerialization.jsonObject(with: path!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
        for city in jsonObject["cities"] as! [[String:AnyObject]] {
            //let coordinates = position["Position"] as! [String:CLLocationDegrees]
            let Cityname = city["name"] as! String

            let Citykind = city["kind"] as! String

            let city = City(name: cityName,description: description, )

            cities.append(city)

        }

    } catch let error as NSError {
        print(error)
    }