简体   繁体   中英

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.

[
  {
    "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

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."

How to decode such JSON response which contents array of dictionaries without a key?

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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