Ios 如何在SwiftUI中处理数组格式的JSON?
我试图从Xcode中获取纬度和经度坐标。我的问题是JSON文件开始时是一个数组,因此我不完全确定如何访问它的所有部分。以下是我的功能:Ios 如何在SwiftUI中处理数组格式的JSON?,ios,json,swift,xcode,api,Ios,Json,Swift,Xcode,Api,我试图从Xcode中获取纬度和经度坐标。我的问题是JSON文件开始时是一个数组,因此我不完全确定如何访问它的所有部分。以下是我的功能: func FetchOriginCoordinates() { let locationUrl = URL(string: "https://nominatim.openstreetmap.org/search?country=Sweden&city=Stockholm&street=odenplan&forma
func FetchOriginCoordinates() {
let locationUrl = URL(string: "https://nominatim.openstreetmap.org/search?country=Sweden&city=Stockholm&street=odenplan&format=json")
URLSession.shared.dataTask(with: locationUrl!) {data, response, error in
if let data = data {
if let decodedJson = try? JSONDecoder().decode([NominationStructure].self, from: data) {
self.originLat = String(decodedJson[0].lat)
self.originLon = String(decodedJson[0].lon)
}
}
}.resume()
}
我试着在网上查找如何编写struct
,这就是我发现的,但我没有工作
struct NominationStructure: Decodable {
var lat: Float
var lon: Float
enum CodingKeys: String, CodingKey {
case lat = "lat"
case lon = "lon"
}
}
你正在扔掉对你有帮助的错误。摆脱
try?
并使用do/try/catch
-然后可以在catch
块中print(error)
,而JSONDecoder
将告诉您出了什么问题,即与lat
和lon
键关联的值是字符串,而不是浮点数。您需要自己将这些值转换为浮点数。@Paulw11哦,我明白了。从现在起,我将一直使用catch
。谢谢你的帮助!