json - 对 GMSCoordinateBounds 数组的 Swift 解码 JSON 响应
问题描述
在我的应用程序中,我有以下 JSON 响应和代表活动工作区域的结构
JSON:
{
"status_code": 1000,
"data": [
{
"name": "BWME23DW",
"north_east_lat": 33.34534,
"north_east_lng": 44.56467
"south_west_lat": 34.89434,
"south_west_lng": 44.54567
},
],
"message": null
}
结构:
import Foundation
import CoreLocation
import GoogleMaps
struct ActiveBounds : Codable {
var status_code : Int!
var data : [LatLngBounds]!
var message : String!
}
struct LatLngBounds : Codable{
var name : String!
var north_east_lat : CLLocationDegrees!
var north_east_lng : CLLocationDegrees!
var south_west_lat : CLLocationDegrees!
var south_west_lng : CLLocationDegrees!
enum CodingKeys: String, CodingKey {
case name
case north_east_lat
case north_east_lng
case south_west_lat
case south_west_lng
}
}
解码响应后,我需要检查用户当前位置是否在活动范围内,这很容易使用GMSCoordinateBounds.contains(latLong)
,所以我如何直接在我的 ActiveBounds 结构中解码和初始化它,以将数据属性作为 GMSCoordinateBounds 数组而不是 LatLngBounds 返回结构
这就是我想要完成的
import Foundation
import CoreLocation
import GoogleMaps
struct ActiveBounds : Codable {
var status_code : Int!
var data : [GMSCoordinateBounds]!
var message : String!
}
解决方案
无需!
在属性末尾写...
更简单的方法是ActiveBounds
在将转换[LatLngBounds]
为[GMSCoordinateBounds]
.
struct ActiveBounds : Codable {
var status_code : Int
var data: [LatLngBounds]
var message: String
lazy var coordinatesBounds: [GMSCoordinateBounds] = {
data.map { GMSCoordinateBounds(coordinate: CLLocationCoordinate2D(latitude: $0.north_east_lat,
longitude: $0.north_east_lng),
coordinate: CLLocationCoordinate2D(latitude: $0.south_west_lat,
longitude: $0.south_west_lng) }
}()
}
这样,您就不会“更改”需要 custom 的 JSON 模型init(from decoder:)
。
推荐阅读
- json - 使用 python 将值从 JSON 传输到 Google 工作表
- javascript - 创建一个函数,该函数将格式化字符串以始终在小数点后显示两位有效数字,无需方法
- java - 在netbeans中编译期间的Maven错误
- javascript - 从另一个页面获取元素
- java - 正则表达式用于在不被单引号或双引号包围时使用空格和特殊字符分割字符串
- php - 用户 'database username'@'%' 拒绝访问数据库 'information_schema'
- c++ - 如果可能,总是更喜欢 std::string(ptr, size) 到 std::string(first, last) ?
- spring - RestEasy 端点抛出 java.lang.NoSuchMethodError: org.codehaus.jackson.map.ObjectMapper.constructType
- node.js - 使用 Puppeteer 捕获表格元素并与之交互
- css - 如何在 django 中有条件地向元素添加 css 类?