【发布时间】:2018-04-27 15:15:31
【问题描述】:
我正在尝试使用 Codable 来解析 JSON 数据。但是当涉及到带有数组的对象时会遇到一些问题。我一直在尝试关注answer,但我收到错误Type 'Feature' does not conform to protocol 'Encodable'
我想要的 JSON 数据是纬度和经度数据,但我正在努力学习Codable。我还可以补充一点,我尝试获取 id 并且效果很好,但是当我尝试更深入时,它只会给我一个错误。
有什么建议吗?我确实想使用Codable 而不是JSONSerialization。
我的结构(到目前为止)
struct Features: Codable {
var features: [Feature]
}
struct Feature: Codable {
var lat: Double
var long: Double
enum CodingKeys: String, CodingKey {
case geometry
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
let geometry = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .geometry)
var coordinates = try geometry.nestedUnkeyedContainer(forKey: .geometry)
long = try coordinates.decode(Double.self)
lat = try coordinates.decode(Double.self)
}
}
JSON 响应
{
"type":"FeatureCollection",
"totalFeatures":1761,
"features":[
{
"type":"Feature",
"id":"LTFR_P_RORELSEHINDRADE.3179814",
"geometry":{
"type":"LineString",
"coordinates":[
[
17.929374,
59.387507
],
[
17.929364,
59.387493
]
]
},
"geometry_name":"GEOMETRY",
"properties":{
"FID":3179814,
"FEATURE_OBJECT_ID":2406812,
"FEATURE_VERSION_ID":1,
"EXTENT_NO":2,
"VALID_FROM":"2008-10-09T22:00:00Z",
"CITATION":"0180 2008-09122",
"STREET_NAME":"Visbyringen",
"CITY_DISTRICT":"Rinkeby",
"PARKING_DISTRICT":"<Område saknas>",
"ADDRESS":"Visbyringen 4",
"VF_METER":12,
"VF_PLATS_TYP":"Reserverad p-plats rörelsehindrad",
"RDT_URL":"https://rdt.transportstyrelsen.se/rdt/AF06_View.aspx?BeslutsMyndighetKod=0180&BeslutadAr=2008&LopNr=09122"
}
}
]
}
感兴趣的数据
"coordinates":[
[
17.929374,
59.387507
],
[
17.929364,
59.387493
]
]
【问题讨论】:
-
它会给你什么错误?
-
如上所述:
Type 'Feature' does not conform to protocol 'Encodable@Andy