【问题标题】:How to decode a property with type of Array of dictionary in Swift 5 decodable protocol without key?如何在没有密钥的 Swift 5 可解码协议中解码字典数组类型的属性?
【发布时间】:2020-10-19 04:59:29
【问题描述】:

以下 JSON 响应没有字典数组的键和内容。

[
  {
    "content": "You can't program the monitor without overriding the mobile SCSI monitor!",
    "media": [
      {
        "title": "Bedfordshire backing up copying",
      }
    ],
    "user": [
      {
        "name": "Ferne",
      }
    ]
  }
]

我正在尝试使用 Decodable 协议使用以下结构来解码此 JSON

struct Articles: Decodable {
  var details: ArticleDetails
  
  init(from decoder: Decoder) throws {
    let container = try decoder.singleValueContainer()
    details = try container.decode(ArticleDetails.self)
  }
}

struct ArticleDetails: Decodable {
  var content: String
  var media: [Media]
  var user: [User]
  
  enum Keys: String, CodingKey {
    case content
    case media
    case user
  }
  
  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: Keys.self)
    content = try container.decode(String.self, forKey: .content)
    media = try container.decode([Media].self, forKey: .media)
    user = try container.decode([User].self, forKey: .user)
  }
}

struct Media: Decodable {
  var title: String
  
  enum Keys: String, CodingKey {
    case title
  }
  
  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: Keys.self)
    title = try container.decode(String.self, forKey: .title)
  }
}

struct User: Decodable {
  var name: String
  
  enum Keys: String, CodingKey {
    case name
  }
  
  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: Keys.self)
    name = try container.decode(String.self, forKey: .name)
  }
}

并使用下面的方法解码响应

let response = try JSONDecoder().decode(Articles.self, from: data)

let response = try JSONDecoder().decode([ArticleDetails].self, from: data)

但出现错误

"应解码 Dictionary 但找到一个字符串/数据 而是。”

如何解码这样的 JSON 响应,其中没有键的字典内容数组?

【问题讨论】:

  • 只有当您想更改可解码变量名称时才使用键枚举。
  • 您的数据以数组的形式出现。所以后者是正确的。

标签: ios json swift dictionary codable


【解决方案1】:

型号:

struct Articles: Decodable {
    let content: String
    let media: [Media]
    let user: [User]
}

struct Media: Decodable {
    let title: String
}

struct User: Decodable {
    let name: String
}

解码:

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

(这已经在您之前的帖子中发布过。已被删除。)

【讨论】:

  • 我觉得很好。
  • @Frankenstein - 以前您使用的是可编码协议,如您所知,它不起作用,我已经回复了您的答案。为了保持问题的清洁和回答,我删除了旧问题并添加了新问题。我希望您能理解我的问题的 +1。现在你的回答真的对我有用。谢谢 :) 因此为您的回答点赞。
猜你喜欢
  • 2017-11-20
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
相关资源
最近更新 更多