没有与键CodingKeys关联的值

时间:2020-04-01 11:31:58

标签: json swift parsing codable

我正在尝试解析以下json:

"categories": [
        {
            "id": 42,
            "name": "Air Conditioning",
            "image_url": "system-data/category/Category-AirConditioning.png",
            "image_marker_url": "system-data/category/Marker_Category-Air Conditioning.png",
            "status_id": 7,
            "created_at": 1580452213,
            "updated_at": 1580452213
        },
        {
            "id": 43,
            "name": "Car Wash",
            "image_url": "system-data/category/Category-Carwash.png",
            "image_marker_url": "system-data/category/Marker_Category-Car Wash.png",
            "status_id": 7,
            "created_at": 1580452213,
            "updated_at": 1580452213
        },
        {
            "id": 45,
            "name": "Automobile Services",
            "image_url": "system-data/category/Category-Automobile.png",
            "image_marker_url": "system-data/category/Marker_Category-Automobile Services.png",
            "status_id": 7,
            "created_at": 1580452213,
            "updated_at": 1580452213
        },
        {
            "id": 48,
            "name": "Electrical",
            "image_url": "system-data/category/Category-Electrical.png",
            "image_marker_url": "system-data/category/Marker_Category-Electrical.png",
            "status_id": 7,
            "created_at": 1580452213,
            "updated_at": 1580452213
        },
        {
            "id": 49,
            "name": "Generator Repair & Maintenance",
            "image_url": "system-data/category/Category-Generator.png",
            "image_marker_url": "system-data/category/Marker_Category-Generator Repair & Maintenance.png",
            "status_id": 7,
            "created_at": 1580452213,
            "updated_at": 1580452213
        }
    ]

下面是将json响应映射到模型中的结构:

struct CityCategory: Codable{

    let id: Int
    let name, imageUrl, imageMarkerUrl: String
    let statusID, createdAt, updatedAt: Int

    enum CodingKeys: String, CodingKey{
        case id = "id"
        case name = "name"
        case imageUrl = "image_url"
        case imageMarkerUrl = "image_marker_url"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case statusID = "status_id"
    }

}

struct CityCategoryResponse: Codable{
    let cityCat: [CityCategory]
}

我正在尝试:

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

它会引发错误。

keyNotFound(CodingKeys(stringValue:“ cityCat”,intValue:nil), Swift.DecodingError.Context(codingPath:[],debugDescription:“否 与键CodingKeys(stringValue:\“ cityCat \”, intValue:nil)(\“ cityCat \”)。“,底层错误:nil))

1 个答案:

答案 0 :(得分:2)

您需要

let categories: [CityCategory]

struct CityCategoryResponse: Codable{
    let cityCat: [CityCategory] 

  enum CodingKeys: String, CodingKey{
        case cityCat = "categories" 
    }
}

cityCat不是json中的密钥,因此解码器找不到它

相关问题