gpt4 book ai didi

iOS swift 将 JSON 分离成数组

转载 作者:行者123 更新时间:2023-11-28 16:05:54 24 4
gpt4 key购买 nike

我有一个像这样的 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],...]

我该怎么做?

附言我使用SwiftyJson

最佳答案

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

关于iOS swift 将 JSON 分离成数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com