我正在开发一个应用程序,它可以读取购物中心的名称和协调。然后将它们与用户的当前位置进行比较,以便用户只能看到他周围最近的购物中心。出于这个原因,我想将所有的名称和位置分成2个数组,并将它们与用户的当前位置进行比较。然后我会准备他们为segue并将他们发送到我的TableViewController
我将在不同的单元格中显示他们的每个人。
我是Swift的新手,如果有人能帮我怎么做,我会很高兴。
我的JSON文件是:
{
"People": {
"Person0": {
"A1": "New York",
"B1": "ShoppingMall1",
"C1": "43.0757",
"D1": "23.6172"
},
"Person1": {
"A1": "London",
"B1": "ShoppingMall2",
"C1": "44.0757",
"D1": "24.6172"
},
"Person2": {
"A1": "Paris",
"B1": "ShoppingMall3",
"C1": "45.0757",
"D1": "25.6172"
},
"Person3": {
"A1": "Bern",
"B1": "ShoppingMall4",
"C1": "41.0757",
"D1": "21.6172"
},
"Person4": {
"A1": "Sofia",
"B1": "ShoppingMall5",
"C1": "46.0757",
"D1": "26.6172"
}
}
}
答案 0 :(得分:0)
斯威夫特3:
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
Swift 2:
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
然后你有一本字典,你可以像这样访问你的人:
let dict = convertStringToDictionary(jsonText)
print(dict["People"])
使用你的json,你不能拥有一个数组,因为你应该改变这样的json:
{
"People": [{
"A1": "New York",
"B1": "ShoppingMall1",
"C1": "43.0757",
"D1": "23.6172"
},
{
"A1": "London",
"B1": "ShoppingMall2",
"C1": "44.0757",
"D1": "24.6172"
}, {
"A1": "Paris",
"B1": "ShoppingMall3",
"C1": "45.0757",
"D1": "25.6172"
}, {
"A1": "Bern",
"B1": "ShoppingMall4",
"C1": "41.0757",
"D1": "21.6172"
}, {
"A1": "Sofia",
"B1": "ShoppingMall5",
"C1": "46.0757",
"D1": "26.6172"
}
]
}