通过 Codable 将 JSON 解析为数组

Dmi*_*nko 0 json swift codable

我有以下 JSON:

\n
[\n{\n "id": 1,\n "type": "Feature",\n "geometry": {\n     "type": "Point",\n     "coordinates": [\n         37.5741167,\n         55.7636592\n     ]\n },\n "properties": {\n     "hintContent": "\xd0\xbf\xd0\xb5\xd1\x80\xd0\xb5\xd1\x83\xd0\xbb\xd0\xbe\xd0\xba \xd0\x92\xd0\xbe\xd0\xbb\xd0\xba\xd0\xbe\xd0\xb2, 13\xd1\x811",\n     "balloonContentHeader": "\xd0\xbf\xd0\xb5\xd1\x80\xd0\xb5\xd1\x83\xd0\xbb\xd0\xbe\xd0\xba \xd0\x92\xd0\xbe\xd0\xbb\xd0\xba\xd0\xbe\xd0\xb2, 13\xd1\x811"\n }\n]\n
Run Code Online (Sandbox Code Playgroud)\n

我正在尝试使用 JSONDecoder:

\n
struct Point : Codable {\n    let id: Int\n    let type: String\n    let properties: Properties\n}\nstruct Properties : Codable {\n    let hintContent: String\n    let balloonContentHeader: String\n}\nstruct Points : Codable {\n    var data : [Point]\n}\n\n\n\nfunc parse(fileName: String) {\n\n    let url = Bundle.main.url(forResource: fileName, withExtension: "json")\n    let data = try? Data(contentsOf: url!)\n    if let jsonPoints = try? JSONDecoder().decode([Point].self, from: data!) {\n        print(jsonPoints)\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

怎么了?

\n

jn_*_*pdx 5

  1. 确保您的 JSON 有效 - 这个 JSON 缺少}.

  2. 将您的(有效)JSON 粘贴到 app.quicktype.io 以生成模型,即。确保您的模型与 JSON 匹配。如果您的 JSON 无效,该网站也会向您发出警告。

  3. 始终使用do/try/catchand nottry?以便在 JSON 解码失败时得到有意义的错误。


let data = """
[
{
 "id": 1,
 "type": "Feature",
 "geometry": {
     "type": "Point",
     "coordinates": [
         37.5741167,
         55.7636592
     ]
 },
 "properties": {
     "hintContent": "t",
     "balloonContentHeader": "t"
 }
}
]
""".data(using: .utf8)

struct Point: Codable {
    let id: Int
    let type: String
    let geometry: Geometry
    let properties: Properties
}

// MARK: - Geometry
struct Geometry: Codable {
    let type: String
    let coordinates: [Double]
}

// MARK: - Properties
struct Properties: Codable {
    let hintContent, balloonContentHeader: String
}

func parse(fileName: String) {
    do {
        let jsonPoints = try JSONDecoder().decode([Point].self, from: data!)
        print(jsonPoints)
    } catch {
        print(error)
    }
    
}
Run Code Online (Sandbox Code Playgroud)

如果没有调整后的 JSON,您的原始代码将在块中生成以下错误catch

给定的数据不是有效的 JSON...字符 224 周围的对象格式错误。

  • @ElTomato `"""` 在 Swift 中启动多行字符串文字 (5认同)