首页 > 解决方案 > JSON Swift.DecodingError.keyNotFound(Swift 5.3)

问题描述

我是 Swift 的新手,我正在尝试解码 JSON,但它不起作用。

这是 JSON 代码:

[
  {
    "LocalObservationDateTime": "2021-02-09T21:11:00+01:00",
    "EpochTime": 1612894260,
    "WeatherText": "Sunny",
    "WeatherIcon": 36,
    "HasPrecipitation": false,
    "IsDayTime": false,
    "Temperature": {
      "Metric": {
        "Value": 15.2,
        "Unit": "C",
        "UnitType": 17
      },
      "Imperial": {
        "Value": 59,
        "Unit": "F",
        "UnitType": 18
      }
    },
    "MobileLink": "http://m.accuweather.com/",
    "Link": "http://www.accuweather.com/"
  }
]

这是我创建的结构:

struct CurrentConditions : Decodable{
    let localObservationDateTime: String?
    let epochTime: Int
    let weatherText: String
    let weatherIcon: Int
    let hasPrecipitation: Bool
    let isDayTime: Bool
    let temperature: Temperature
}

struct Temperature : Decodable{
    let metric: Metric
    let imperial: Imperial
}

struct Imperial : Decodable{
    let value: Int
    let unit: String
    let unitType: Int
}

struct Metric : Decodable{
    let value: Double
    let unit: String
    let unitType: Int
}

let response = try! JSONDecoder().decode(CurrentConditions.self, from: jsonData)

我使用此代码进行解码,但所有变量均为零。

图片

解码器可以解决结构,但它是零。当我将“CurrentConditions”放入数组中时(如下所示:[CurrentConditions]),解码器无法解决结构和对象(响应)为零。

Fatal error: 'try!' expression unexpectedly raised an error:
Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>,
Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode
Dictionary<String, Any> but found an array instead.", underlyingError: nil)): file
JSON_Test/ViewController.swift, line 52
2021-02-10 13:13:22.429097+0300 JSON Test[7884:534414] Fatal error: 'try!' expression
unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String,
Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode
Dictionary<String, Any> but found an array instead.", underlyingError: nil)): file
JSON_Test/ViewController.swift, line 52

标签: jsonswift

解决方案


您的内容是数组而不是字典,您需要[CurrentConditions].self

do {
     let response = try JSONDecoder().decode([CurrentConditions].self, from: jsonData)
 }
catch {
  print(error) 
}

始终避免try!和使用do catch


推荐阅读