从字典中获取密钥到嵌套的可解码模型中

问题描述

假设我们有一个这样的 JSON:

{
  "id1": {
    "name": "hello"
  },"id2": {
    "name": "world"
  }
}

模型:

struct Model: Decodable {
  var id: String
  var name: String
}

如何从上面的 JSON 生成一个 Model 数组?

解决方法

你可以这样做

let data = """
{
  "id1": {
    "name": "hello"
  },"id2": {
    "name": "world"
  }
}
""".data(using: .utf8)!


struct Name: Decodable {
    let name: String
}

struct Model {
    let id: String
    let name: String
}

do {
    let json = try JSONDecoder().decode([String: Name].self,from: data)
    let result = json.map { Model(id: $0.key,name: $0.value.name) }
    print(result)
} catch {
    print(error)
}

我们将数据解码为 [String,Name]。我们可以将其解码为 [String: [String:String]] 但这意味着我们将不得不处理可选值,因此更容易创建 Name 结构来处理该部分。

一旦我们有了字典,我们就将它映射到模型对象中,留下一个 [Model] 数组