json - 使用 Alamofire 和 Swift 返回嵌套 JSON 数组中的值
问题描述
对 swift、JSON 和几乎所有编码来说都是超级新手,所以如果这个问题对网站上的其他人来说是多余的,或者我在这里遗漏了一些简单的东西,我提前道歉。
我希望在下面的 JSON 代码中的“元素”数组中返回与“距离”相关的“文本”(“1.7 英里”)的值:
{
"destination_addresses" : [ "30 Rockefeller Plaza, New York, NY 10112, USA" ],
"origin_addresses" : [ "352 7th Ave, New York, NY 10001, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1.7 mi",
"value" : 2729
},
"duration" : {
"text" : "15 mins",
"value" : 887
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
我使用 Alamofire 和 Google DistanceMatrix 检索了 JSON 数据(请参阅下面的代码),但是在解析数据以隔离我需要的内容时遇到了麻烦。我知道下面的代码并不接近我需要的,但不确定如何继续。
func distanceMatrix(startLocation: String, endLocation: String) {
let myOrigin = startLocationTFText
let myDestination = destinationLocationTFText
let url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=\(myOrigin)&destinations=\(myDestination)&key=API_Key
let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
AF.request(encodedUrl!).responseJSON { response in
print(response.request as Any)
print(response.response as Any)
print(response.data as Any)
print(response.result as Any)
let json = JSON(response.data as Any)
任何帮助深表感谢。谢谢你。
解决方案
您可以使用Decodable
来获得所需的结果。
struct RootResponse: Decodable {
let destinationAddresses, originAddresses: [String]
let rows: [Rows]
let status: String
}
struct Rows: Decodable {
let elements: [Elements]
}
struct Elements: Decodable {
let distance, duration: Details
let status: String
}
struct Details: Decodable {
let text, value: String
}
这将是您的模型文件,一旦您添加了它,您就可以返回到您的函数并将其用作:
func distanceMatrix(startLocation: String, endLocation: String) {
let myOrigin = startLocationTFText
let myDestination = destinationLocationTFText
let url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=\(myOrigin)&destinations=\(myDestination)&key=API_Key"
let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
AF.request(encodedUrl!).responseJSON { response in
print(response.request as Any)
print(response.response as Any)
print(response.data as Any)
print(response.result as Any)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard let json = try? decoder.decode(RootResponse.self, from: response.data) else { print("Unable to parse JSON"); return }
print(json)
print(json.rows.first?.elements.first?.distance.value) // This is how you can get the value, but it will be better to safely unwrap them and I have also used first? to get the first object but this is an array and you can always use a for loop for further purpose
}
推荐阅读
- javascript - Javascript 错误:“无法读取未定义的属性零”
- google-chrome-extension - 将 google 优化与 chrome 扩展集成时遇到不同的错误
- laravel-8 - 如何用 min 获取行数据
- reactjs - 如何在 React 中添加到父事件处理程序
- python - 挣扎于 While 循环
- java - 什么
应该为这些方法添加标签吗? - javascript - 如何使用javascript中的过滤器根据性别过滤掉对象数组?
- unity3d - 哪个是在 Unity2D 中创建像素艺术的最佳应用程序?
- java - 修复:线程“main”中的异常 java.lang.NumberFormatException:对于输入字符串:“”
- javascript - 单击按钮时如何淡入div?