SwiftUI-类型“服务”不符合协议“可解码”

时间:2019-07-18 12:35:53

标签: json swift swiftui codable

我正在使用一个正在构建的小应用程序来使用SwiftUI,但是我遇到了Codable的问题,并且遇到了一些错误。

我有一个看起来像这样的JSON文件

[
    {
        "id": "",
        "name": "services",
        "items": [
            {
                "id": 0
                "businessName": "Some Name",
                "businessTelephone": "01234567890",
                "businessEmail": "email@gmail.com",
                "businessWebsite": "website.com",
                "businessLocation": { "latitude": "54.137256", "longitude": "-1.524727" },
                "travelLimit": 50,
                "description": "A description about some business",
                "categories": ["Category 1"]
            }
    }
]

我有一个看起来像这样的结构

struct Service: Hashable, Codable, Identifiable { 

    var id: Int
    var businessName: String
    var businessTelephone: String
    var businessEmail: String
    var businessWebsite: String
    var businessLocation: Array<Any>
    var travelLimit: Int
    var description: String
    var categories: [Category]

    enum Category: String, CaseIterable, Hashable, Codable {

        case category1 = "Category 1"
        case category2 = "Category 2"

    }

}

但是,出现以下错误

Type 'Service' does not conform to protocol 'Decodable'
Type 'Service' does not conform to protocol 'Encodable'
Type 'Service' does not conform to protocol 'Equatable'
Type 'Service' does not conform to protocol 'Hashable'

1 个答案:

答案 0 :(得分:1)

Codable不能有Any,加上businessLocation是字典而不是数组,因此请替换

var businessLocation: Array<Any>

使用

var businessLocation:[String:String]

OR

模型

// MARK: - Element
struct Root: Codable {
    let id, name: String
    let items: [Item]
}

// MARK: - Item
struct Service: Codable {
    let id: Int
    let businessName, businessTelephone, businessEmail, businessWebsite: String
    let businessLocation: BusinessLocation
    let travelLimit: Int
    let itemDescription: String
    let categories: [String]

    enum CodingKeys: String, CodingKey {
        case id, businessName, businessTelephone, businessEmail, businessWebsite, businessLocation, travelLimit
        case itemDescription = "description"
        case categories
    }
}

// MARK: - BusinessLocation
struct BusinessLocation: Codable {
    let latitude, longitude: String
}

解码

do {
    let res = try JSONDecoder().decode([Root].self, from: data)
    print(res)
}
catch {
    print(error)
}