arrays - 快速解码:预期解码数组但找到了一本字典
问题描述
我从许多不同的文章中尝试了许多不同的方法,但我无法从 HTTP 响应中解码这个 JSON。
有人可以帮我吗?
谢谢。
JSON: 这是数据 URL 返回的 JSON:
{
"@odata.context": "$metadata#GeoFences(Points())",
"value": [
{
"ID": "69d5513c-c1f1-4f5d-aef5-184a913484be",
"GEOFENCE_NAME": "Dragon Park",
"GEOFENCE_TYPE": "C",
"PRIVACY": "X",
"CENTER_LAT": 32.92536134246622,
"CENTER_LONG": -117.01864890726854,
"ZOOM_LAT": 0.007421265080928663,
"ZOOM_LONG": 0.006358979598971359,
"PATH_TOLERANCE": 5,
"ENTRANCE_TOLERANCE": 5,
"Points": {
"POINT_TYPE": "E",
"POINT_NUM": 0,
"LATITUDE": 32.924186548800414,
"LONGITUDE": -117.0213193658842,
"parent_ID": "69d5513c-c1f1-4f5d-aef5-184a913484be"
}
}
]
}
结构: 这些是我想要解码的冲突。我希望具有嵌入点结构的值结构。
struct Value: Decodable {
let id: String?
let geofenceName: String?
let geofenceType: String?
let privacy: String?
let centerLat: Double?
let centerLong: Double?
let zoomLat: Double?
let zoomLong: Double?
let pathTolerance: Double?
let entranceTolerance: Double?
let points: GeoFencePointData
enum CodingKeys: String, CodingKey {
case id = "ID"
case geofenceName = "GEOFENCE_NAME"
case geofenceType = "GEOFENCE_TYPE"
case privacy = "PRIVACY"
case centerLat = "CENTER_LAT"
case centerLong = "CENTER_LONG"
case zoomLat = "ZOOM_LAT"
case zoomLong = "ZOOM_LONG"
case pathTolerance = "PATH_TOLERANCE"
case entranceTolerance = "ENTRANCE_TOLERANCE"
case points = "Points"
}
}
struct GeoFencePointData: Codable {
var pointType: String
var pointNum: Int
var latitude: Double
var longitude: Double
var parentID: String
enum CodingKeys: String, CodingKey {
case pointType = "POINT_TYPE"
case pointNum = "POINT_NUM"
case latitude = "LATITUDE"
case longitude = "LONGITUDE"
case parentID = "parent_ID"
}
}
Swift 代码: 似乎这是用于解码 JSON 的典型代码。我想主要的并发症是响应是一个数组。
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
print("Data: \(data)")
do {
let decoder = JSONDecoder()
let allGeoFences = try decoder.decode([Value].self, from: data)
print(allGeoFences)
} catch {
print("error: \(error)")
}
}
解决方案
推荐阅读
- swift - 安全区域在自定义 TabBarController 的 ViewController 中不起作用
- c++ - 如何范围检查 C++14 用户定义的文字?
- php - 在 Symfony 中保持 const 值
- audio - 我的音频控制显示,但它没有播放
- sql - SQL Join - 从外键表中获取符合条件的行
- html - 侧边菜单中的子菜单
- python - Python没有将整个输出写入文件
- vuejs2 - 停止在 div 内传播 div
- amazon-dynamodb - 将访问控制与 IAM 策略结合使用时的 DynamoDB 和 GSI
- android - Android 中的 TagManager:无法加载容器。未找到资源 ID -1 的默认容器资源