Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/97.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在SwiftUI中处理数组格式的JSON?_Ios_Json_Swift_Xcode_Api - Fatal编程技术网

Ios 如何在SwiftUI中处理数组格式的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

我试图从Xcode中获取纬度和经度坐标。我的问题是JSON文件开始时是一个数组,因此我不完全确定如何访问它的所有部分。以下是我的功能:

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
。谢谢你的帮助!