【发布时间】:2021-09-24 12:14:14
【问题描述】:
在我的应用中,我有以下 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!
}
【问题讨论】:
-
GMSCoordinateBounds是从 2 个坐标创建一个矩形,不是吗?只有1个坐标怎么能初始化?但我建议您在ActiveBounds上创建一个计算变量,将[LatLngBounds]转换为[GMSCoordinateBounds]。 -
对不起,我复制了错误的代码,我更新它
-
您真的需要将它放在变量
data中吗?或者它可以是另一个属性?因为目前,GMSCoordinateBounds也需要是Codable。如果您不使用它,但只能在您的模型中使用... -
我会为 GMSCoordinateBounds 属性使用单独的模型,而不是更改或扩展您的 json 相关结构,如果您想添加新的属性/功能,我认为这将是一个更简洁的解决方案并且更容易修改。另外,一旦 json 被正确解码,你真的关心那个状态码和(错误?)消息吗?
-
@Larme 可以在另一个属性中,我只想将它作为数组访问以在我的控制器中循环以检查当前位置是否在活动区域之一内
标签: json swift jsondecoder