【问题标题】:Swift - key not found error while Json decodingSwift - Json解码时找不到密钥错误
【发布时间】:2021-10-18 17:51:42
【问题描述】:

Swift 中 Json 的问题 - 尝试解码数据,但出现错误“未找到密钥”。 我用另一个键检查过 - 它可以工作,所以可能是名称错误?

如有任何提示,我将不胜感激!

json:

{
"created": "2021-10-18T14:55:42.537Z",
"count": 2,
"offset": 0,
"places": [
{
"id": "d1ab65f8-d082-492a-bd70-ce375548dabf",
"type": "Studio",
"type-id": "05fa6a09-ff92-3d34-bdbb-5141d3c24f38",
"score": 100,
"name": "Chipping Norton Recording Studios",
"address": "28–30 New Street, Chipping Norton",
"coordinates": {
"latitude": "51.9414",
"longitude": "-1.548"
},
"area": {6 items},
"life-span": {
"begin": "1971",
"end": "1999-10",
"ended": true
}
},
{8 items}
]
}

还有我的数据结构:

import Foundation

struct BrainzData: Codable {
    let places: [Places]
}

struct Places: Codable {
    var coordinates: Coordinates
    var lifespan: LifeSpan
    
    enum CodingKeys: String, CodingKey {
        case coordinates
        case lifespan = "life-span"
    }
}

struct Coordinates: Codable {
    let longitude: String
    let latitude: String
}

struct LifeSpan: Codable {
    let begin: String
    var ended: Bool
}

【问题讨论】:

  • 完整的错误信息是什么?会不会是 JSON 中缺少值的地方之一,而在您提供的示例中它是正确的?
  • ...您使用特定的密钥解码策略吗?
  • 我不确定我是否得到你,但正确的样本是“id”。所以我得到了价值。结构也是以同样的方式构建的。完整的错误消息:keyNotFound(CodingKeys(stringValue: "begin", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "places", intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "life-span", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: \"begin\", intValue: nil) (\"begin\") .",基础错误:无))
  • 错误涉及数组places 中的第二个 项(索引1),这是不可见{8 items} 中的第一个
  • 读取 JSON。如果缺少键(在数组项中),则将相应的结构成员声明为可选。

标签: json swift


【解决方案1】:

尝试解码来自 api 的所有数据,您可能会看到一些键值对为空。您可能希望将参数更改为可选。所以首先改变你的结构为

struct Coordinates: Codable {
    let longitude: String?
    let latitude: String?
}

struct LifeSpan: Codable {
    let begin: String?
    var ended: Bool?
}

然后记录您的数据,例如:

guard let responseData = data else { return }
                     do {
                         let jsonData = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers)
                         let apiResponse = try JSONDecoder().decode(BrainzData.self, from: responseData)
                         print(apiResponse)
                        
                    } catch {
                     print(error)
}

session.dataTask func中的数据是一样的

task = session.dataTask(with: request, completionHandler: { data, response, error in })

【讨论】:

  • mutableContainers 在 Swift 中毫无意义,尤其是当您将结果分配给 im 可变常量时。
  • 那么,您可以只使用 var 关键字使对象可变。
  • 是的,该选项仅在 Objective-C 中有意义。在 Swift 中它完全没用。删除options参数。
  • 非常感谢!!!它终于奏效了! :) 不,例如我有 3 个不同的纬度值。我如何才能找到它们并在控制器中使用?请问您能否提供一个提示如何从 JSON 构造数据?我应该列个清单吗?
猜你喜欢
  • 1970-01-01
  • 2023-02-11
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多