首页 > 解决方案 > 快速解码:预期解码数组但找到了一本字典

问题描述

我从许多不同的文章中尝试了许多不同的方法,但我无法从 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)")
   }
}

标签: arraysjsonswiftdecodecodable

解决方案


推荐阅读