ios - Swift 5 中的 JSON 对象
问题描述
我正在尝试访问 json api 中的数据,如下所示
"Products": [
{
"ProductName": "GR",
"ShortDescription": "General service epoxy mortar system that utilizes recycled glass and rapidly renewable soy based components.",
"PDSOverride": [
{
"FileName": "EcoLab Netherlands",
"FileUrl": "http://test.stonhard.com/media/2264/eco-lab-netherlands-usa-version.pdf"
},
{
"FileName": "General Dynamics.pdf",
"FileUrl": "http://test.stonhard.com/media/2060/general-dynamics.pdf"
}
]
}
]
我在下面这样的结构中对此进行建模
struct Solutions: Codable, Identifiable {
let id = UUID()
let SectionTitle: String
let SectionImage: String
let ProductLines: [ProductLine]
}
struct ProductLine: Codable {
let System: String
let Products: [Product]
}
struct Product: Codable {
let ProductName: String
let ShortDescription: String
let PDSOverride: [PDSOverride]
}
struct PDSOverride: Codable {
let FileName: String
let FileUrl: String
}
struct SdsPdf: Codable {
let FileName: String
let FileUrl: String
}
struct GuideSpecPdf: Codable {
let FileName: String
let FileUrl: String
}
当我尝试访问数据时,我收到一条错误消息,指出无法读取数据,因为它的格式不正确。我知道这是我的模型的问题,因为当我注释掉 PDSOverride、SdsPdf 和 GuideSpecPdf 时,它可以工作,但显然我无权访问这些数据。我如何为我的结构建模,以便我可以提取该数据?
解决方案
问题不在您的模型中,您的 JSON 格式错误,正如编译器所说,您的 JSON 需要如下所示:
[
{
"Products": [
{
"ProductName": "GR",
"ShortDescription": "General service epoxy mortar system that utilizes recycled glass and rapidly renewable soy based components.",
"PDSOverride": [
{
"FileName": "EcoLab Netherlands",
"FileUrl": "http://test.stonhard.com/media/2264/eco-lab-netherlands-usa-version.pdf"
},
{
"FileName": "General Dynamics.pdf",
"FileUrl": "http://test.stonhard.com/media/2060/general-dynamics.pdf"
}
]
}
]
}
]
另外,模型可以用这种方式完成,我建议你使用 Quicktype ( https://app.quicktype.io ) 在线版本很好,他们有一个桌面版本:
// MARK: - PurpleProduct
struct PurpleProduct: Codable {
let products: [ProductProduct]
enum CodingKeys: String, CodingKey {
case products = "Products"
}
}
// MARK: - ProductProduct
struct ProductProduct: Codable {
let productName, shortDescription: String
let pdsOverride: [PDSOverride]
enum CodingKeys: String, CodingKey {
case productName = "ProductName"
case shortDescription = "ShortDescription"
case pdsOverride = "PDSOverride"
}
}
// MARK: - PDSOverride
struct PDSOverride: Codable {
let fileName: String
let fileURL: String
enum CodingKeys: String, CodingKey {
case fileName = "FileName"
case fileURL = "FileUrl"
}
}
typealias Products = [PurpleProduct]
要解码,您可以使用 JSONDecoder,我还建议您在此页面中检查您的 json:https ://jsonformatter.curiousconcept.com
推荐阅读
- java - 通过 certbot 允许 https 访问多个端口
- kubernetes - firewalld 命令替代 iptables -P FORWARD ACCEPT
- javascript - 如何通过查询字符串使用多个选项和嵌套项聚合 Mongodb/Mongoose?
- android - Android 中的 Firestore 权限被拒绝
- asp.net-core - 如果我拥有所有服务(没有第三方),使用 Oauth2.0 资源所有者密码凭证的缺点
- node.js - 问:Twilio 星期决定
- django - 如何覆盖模型更新方法
- api - Gmail API 的 OAuth 同意屏幕
- verilog - FSM 条件计数器
- linux - 使用 ls 命令列出超过 X 分钟的文件