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

1
  • update your question with your Method brother Commented Oct 29, 2016 at 4:20

1 Answer 1

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)
    }
Sign up to request clarification or add additional context in comments.

2 Comments

It's been a while now that Swift has stopped using NSError like this for JSON... See stackoverflow.com/a/31073812/2227743
@MohammadReza Then please read the SwiftyJSON documentation, everything is explained. There's also already plenty of similar questions and answers on SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.