【问题标题】:Swift decode json error: keyNotFound [closed]Swift解码json错误:keyNotFound [关闭]
【发布时间】:2018-06-03 12:00:28
【问题描述】:
{
"coord": {
    "lon": -122.03,
    "lat": 37.33
},
"weather": [
    {
        "id": 701,
        "main": "Mist",
        "description": "mist",
        "icon": "50n"
    }
],
"base": "stations",
"main": {
    "temp": 287.01,
    "pressure": 1012,
    "humidity": 77,
    "temp_min": 282.15,
    "temp_max": 290.15
},
"visibility": 16093,
"wind": {
    "speed": 1.5,
    "deg": 290
},
"clouds": {
    "all": 1
},
"dt": 1528023600,
"sys": {
    "type": 1,
    "id": 428,
    "message": 0.0042,
    "country": "US",
    "sunrise": 1528030097,
    "sunset": 1528082688
},
"id": 5341145,
"name": "Cupertino",
"cod": 200
}

我尝试使用以下代码将其解码为我的对象:

do {
    let decoder = JSONDecoder()
    let object = try decoder.decode(Object.self, from: data)
    return object
} catch {
    print("JSON Error: \(error)")
    return Object(weather: Weather(), main: Main())
}

这是我的对象:

struct Object: Codable {
    var weather: Weather
    var main: Main
}

struct Weather: Codable {
    var city = ""
    var description = ""
    var icon = ""

    enum CodingKeys: String, CodingKey {
        case city = "name"
        case description = "main"
        case icon
    }
}

struct Main: Codable {
    var temputure = ""

    enum CodingKeys: String, CodingKey {
        case temputure = "temp"
    }
}

但我得到一个错误:

JSON 错误:typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "天气", intValue: nil)], debugDescription: "预计解码 字典,但找到了一个数组。”,基础错误: 无))

我想知道如何解决这个问题。

【问题讨论】:

  • 嗯,错误的描述是这样的:Expected to decode Dictionary but found an array instead。您的 weather 键不是对象,而是对象数组。
  • @MihaiFratu 我该如何解决这个问题?

标签: json swift


【解决方案1】:

CodingKeys(stringValue: "weather", intValue: nil)], debugDescription: "本应解码字典,但找到了一个数组

从调试这个错误你有Weather是一个数组[]不是字典{}

在 Json [] 是数组,{} 是字典

型号:

    struct Object: Codable {
        let weather: [Weather]
        let main: Main
    }
    struct Main: Codable {
        let temp: Double
        let pressure, humidity: Int
        let tempMin, tempMax: Double

        enum CodingKeys: String, CodingKey {
            case temp, pressure, humidity
            case tempMin = "temp_min"
            case tempMax = "temp_max"
        }
    }
    struct Weather: Codable {
        let id: Int
        let main, description, icon: String
    }

使用它:

    do {
    let decoder = JSONDecoder()
    let object = try decoder.decode(Object.self, from: data)
    return object
}  
    catch {
    print("JSON Error: \(error)")
    return Object(weather: Weather(), main: Main())
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多