0

I have a JSON file like this:

{
"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",
    }
  ]
}
}
}

and in my app I need to separate this JSON and insert into a array like this for separate data with tableView section:

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

how can I do that?

P.S I use SwiftyJson

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Mohammadreza
  • 225
  • 5
  • 19

1 Answers1

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)
    }
Dakata
  • 1,227
  • 2
  • 14
  • 33
  • It's been a while now that Swift has stopped using NSError like this for JSON... See http://stackoverflow.com/a/31073812/2227743 – Eric Aya Oct 27 '16 at 14:00
  • @MohammadReza Then please read the SwiftyJSON documentation, everything is explained. There's also already plenty of similar questions and answers on SO. – Eric Aya Oct 27 '16 at 14:30