以下[key:value]对,不适合使用
A_Geo:“MULTIPOINT((121.5831587 24.9971109))”
我需要支持将其转换为字典并像其他对一样组合成字典数组
[_id:1,.....,lng:121.5831587,lat:24.9971109,......]
为了解析以下JSON以将Geo数据分析为lng和lat,我们尝试应用JSONSerialization。但不想进一步。
result:
{
offset: 0,
limit: 10000,
results:[
-{
_id: "1",
A_Name_Ch: “Great Hotel Spot",
A_Geo: "MULTIPOINT ((121.5831587 24.9971109))",
A_Location: “Great Spot",
A_Name_En: "Giant Great",
A_CID: "1"
}, {…}, {…}
}
]
}
let ArticlesUrl = URL (string: "http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=a3e2b221-75e0-45c1-8f97-75acbd43d613")!
let session = URLSession.shared
let task = session.dataTask(with: ArticlesUrl){(data,response,error) in
if let error = error {
print ("failed!!")
completionHandler(nil,error)
return
}
let data = data!
if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as![String:[String: Any]], let articleArray = jsonObject["result"]!["results"] as? [[String: Any]]{
var articles = [Article]()
for articleDict in articleArray{
let article = Article(rawData: articleDict)
articles.append(article)
}
completionHandler(articles, nil)
}
}
task.resume()
答案 0 :(得分:0)
您无法与lat and lng
结合使用,您必须在解析时手动执行此操作。
这是给您的信息。假设你已经解析了A_Geo
值,现在你有了跟随字符串"MULTIPOINT ((121.5831587 24.9971109))"
,你应该这样做,
let string = "MULTIPOINT ((121.5831587 24.9971109))"
let value = string.slice(from: "((", to: "))")
let latitude = value?.components(separatedBy: " ").first
let longitude = value?.components(separatedBy: " ").last
print(latitude!, longitude!)
输出将是,
("121.5831587") ("24.9971109")
以下是slice
的{{1}}泛型函数。
String extension
extension String {
func slice(from: String, to: String) -> String? {
return (range(of: from)?.upperBound).flatMap { substringFrom in
(range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
String(self[substringFrom..<substringTo])
}
}
}
}
是通用函数,只要有这种情况,就可以在整个应用程序的任何地方使用它。
答案 1 :(得分:0)
解析MULTIPOINT
字符串表达式的替代方法是Scanner
let string = "MULTIPOINT ((121.5831587 24.9971109))"
let scanner = Scanner(string: string)
var lat = 0.0, lng = 0.0
if scanner.scanUpToCharacters(from: CharacterSet.decimalDigits, into: nil) {
scanner.scanDouble(&lat)
scanner.scanDouble(&lng)
}
let coordinate = ["lat" : lat, "lng" : lng]
答案 2 :(得分:0)
参考上面的评论和相关文章,我在Swift 4中找到了一个解决方案,尽管这个解决方案很有效。如果有人能够改进它,我将非常感激。
if let geo = article.geo {
print("Geo is \(geo)")
// geo = "MULTIPOINT ((121.5831587 24.9971109))"
let geo_StringA = geo.split(separator: "(", maxSplits: 3)[1]
let geo_StringB = geo_StringA.split(separator: ")", maxSplits: 3)[0]
let geo_array = geo_StringB.split(separator: " ", maxSplits: 3)
let lng_String = String(geo_array.first!) as NSString
let lng = lng_String.doubleValue
self.articles[indexPath.row].lng = lng
print("lng is \(lng)")
let lat_String = String(geo_array.last!) as NSString
let lat = lat_String.doubleValue
self.articles[indexPath.row].lat = lat
print("lat is \(lat)")
}