简体   繁体   English

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

[英]How to decode a property with type of Array of dictionary in Swift 5 decodable protocol without key?

The below JSON response does not have the key and contents the array of dictionaries.下面的 JSON 响应没有字典数组的键和内容。

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

I am trying to decode this JSON using Decodable protocol using below struct我正在尝试使用以下结构使用可解码协议解码此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)
  }
}

and decoding the response using below并使用以下解码响应

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

OR或者

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

but getting the error但得到错误

"Expected to decode Dictionary<String, Any> but found a string/data instead." “预期解码 Dictionary<String, Any> 但找到了一个字符串/数据。”

How to decode such JSON response which contents array of dictionaries without a key?如何解码这样的 JSON 响应哪些字典内容数组没有键?

Model: Model:

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

struct Media: Decodable {
    let title: String
}

struct User: Decodable {
    let name: String
}

Decoding:解码:

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

(This was already posted in your previous post. Which has been deleted.) (这已经在您之前的帖子中发布过。已被删除。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM