gpt4 book ai didi

swift - Codable:通过索引将 JSONArray 解码为特定字段

转载 作者:行者123 更新时间:2023-11-28 15:25:23 24 4
gpt4 key购买 nike

我有这个(恕我直言)JSON

"geometry": {
"type": "Point",
"coordinates": [
6.08235,
44.62117
]
}

我想映射到这个 struct,删除 2 个字段的数组。

struct MMGeometry:Codable {
let type:String
let latitude: Double
let longitude: Double
}

JSONDecoder 能够做到这一点吗?也许使用 CodingKey

最佳答案

我选择了手动解决方案:

struct Geometry:Codable {
let type:String
let latitude: Double
let longitude: Double

enum CodingKeys: String, CodingKey {
case type, coordinates
}

enum CoordinatesKeys: String, CodingKey {
case latitude, longitude
}

init (from decoder :Decoder ) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
type = try container.decode(String.self, forKey: .type)
let coords:[Double] = try container.decode([Double].self, forKey: .coordinates)
if coords.count != 2 { throw DecodingError.dataCorruptedError(forKey: CodingKeys.coordinates, in: container, debugDescription:"Invalid Coordinates") }

latitude = coords[1]
longitude = coords[0]
}

func encode(to encoder: Encoder) throws {

}
}

关于swift - Codable:通过索引将 JSONArray 解码为特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45337686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com