Swift解码json错误:keyNotFound

时间:2018-06-03 12:00:29

标签: json swift

{
"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:   “weather”,intValue:nil)],debugDescription:“预计要解码   字典却找到了一个数组。“,underlyingError:   无))

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

1 个答案:

答案 0 :(得分:0)

  

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())
}