json - SwiftUI - 类型“服务”不符合协议“可解码”
问题描述
我在我正在构建的一个小应用程序上使用 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'
解决方案
Codable
不能有Any
,加号businessLocation
是字典而不是数组,所以替换
var businessLocation: Array<Any>
和
var businessLocation:[String:String]
或者
楷模
// 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)
}
推荐阅读
- python - skimage.external.TiffWriter:命名重要性
- c# - 我怎样才能提高我的“比较”方法效率?
- reactjs - 在 Android 上弹出的 Expo 项目上运行 Realm 并出现错误
- java - 将带有自定义实现方法的通用枚举作为参数传递
- php - 数据附加到产生不正确结果的 php Implode 语句
- linux - Snap 无法运行,snap.tar.gz 已经退出
- java - IDEA intellij 如何停止常量重新格式化?
- android - gradle(右侧)中的Android studio 4.2.1 siginig报告无法找到
- powershell - 使用 Powershell 将文件上传到 Sharepoint Online (Microsoft 365)(选项 3 - 使用 System.Net.WebClient)
- reactjs - TypeError:无法读取注销按钮上未定义链接的属性“推送”