【问题标题】:why JSONDecoder gives typeMismatch for valid json为什么 JSONDecoder 为有效的 json 提供 typeMismatch
【发布时间】:2020-07-09 05:06:57
【问题描述】:

我正在使用 JSONDecoder 将 JSON 转换为对象。

这里是代码。它通常工作正常。

         do{
                print("Hi")
                       if Data != nil{
                        let model =  try JSONDecoder().decode(Base.self, from: Data!)
                       }
            }
            catch{
                print("Error:\(error)")
            }

但我正在低于错误

错误:类型不匹配(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: “棒”,intValue:无),编码键(stringValue:“点头”,intValue:无), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "meta", intValue: nil), CodingKeys(stringValue: "label", intValue: nil)], debugDescription: "预期解码 Double 但发现 字符串/数据。”,基础错误:无))

它曾经工作得很好。任何解决此问题的帮助将不胜感激

【问题讨论】:

  • 请仔细阅读错误信息。这很清楚。字典rod 中数组nod 的第一项中的字典meta 中键label 的值是String,而不是预期的Double

标签: ios json swift jsondecoder


【解决方案1】:

问题似乎是数据类型问题。

您必须调查 JSONDecoder().decode 中的 可解码协议

Base.self

元类/结构成员之一基本上是Double,而它应该是String

我没有做任何广告,但我个人认为https://app.quicktype.io/ 易于使用,并且在为任何 JSON 生成可解码协议时几乎没有错误。

我通常将我的 JSON 复制粘贴到 QuickType 中,它会生成结构来保存我的 JSON 值,然后我将这些结构复制粘贴到我的代码中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2020-05-21
    • 2019-01-06
    相关资源
    最近更新 更多