Ios 在Swift 5可解码协议中,如何在没有密钥的情况下解码字典数组类型的属性?

Ios 在Swift 5可解码协议中,如何在没有密钥的情况下解码字典数组类型的属性?,ios,json,swift,dictionary,codable,Ios,Json,Swift,Dictionary,Codable,下面的JSON响应没有字典数组中的键和内容 [ { "content": "You can't program the monitor without overriding the mobile SCSI monitor!", "media": [ { "title": "Bedfordshire backing up copying",

下面的JSON响应没有字典数组中的键和内容

[
  {
    "content": "You can't program the monitor without overriding the mobile SCSI monitor!",
    "media": [
      {
        "title": "Bedfordshire backing up copying",
      }
    ],
    "user": [
      {
        "name": "Ferne",
      }
    ]
  }
]
我正在尝试使用下面的结构使用可解码的协议来解码这个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)

但是得到了错误

“应解码字典,但找到字符串/数据” 相反。”

如何解码这种JSON响应,它包含没有键的字典数组?

模型:

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。现在你的答案真的对我有用。谢谢:)所以请投票支持你的答案。
do {
    let response = try JSONDecoder().decode([Articles].self, from: data)
    print(response)
} catch { print(error) }