Swift解码:预期对Array <Any>进行解码,但是找到了一个字典

问题描述

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

结构: 这些是我要解读的冲突。我希望具有嵌入点结构的Value结构。

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"
    }
}

快捷代码 似乎这是用于解码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)")
   }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)