我正在尝试了解使用Codable解析json文件的最佳方法。
这是json结构。
{
"type": "Feature",
"features": [
{
"type": "Feature",
"geometry": {
"coordinates": [
[10.23, 48.32],
[10.24, 48.33],
[10.25, 48.34],
[10.26, 48.35],
[10.27, 48.36]
]
}
}
]
}
我需要的是坐标表。我试图实现这种结构,但我遇到了一些问题。
struct Root: Codable {
let features: [Features]
}
struct Features: Codable {
let geometry: [Coordinates]
}
struct Geometry: Codable {
let coordinates: [Coordinates]
}
struct Coordinates: Codable {
let latitude: [Double]
let longitude: [Double]
}
然后我调用类似的JSONDecoder
函数
let coordinates = try JSONDecoder().decode(Root.self, from: data)
我认为错误在于坐标在一个子列表中。我是新来的,如果这个问题有点假,我很抱歉,但我自己还没有找到解释。
你差不多到了。试试这个:
struct Root: Codable {
let features: [Feature]
}
struct Feature: Codable {
let geometry: Geometry
}
struct Geometry: Codable {
let coordinates: [[Double]]
}
和:
let root = try JSONDecoder().decode(Root.self, from: data)
和:
for feature in root.features {
let coords = feature.geometry.coordinates
print("(coords)")
}
PS:你的数据似乎是GeoJSON
。阅读Swift GeoJSON以及如何解码。