【问题标题】:Mapping a variety of JSON responses with the same top - level structure in Swift在 Swift 中使用相同的顶级结构映射各种 JSON 响应
【发布时间】:2021-05-19 18:16:29
【问题描述】:

我通过 Alamofire 从服务器返回了各种 JSON 响应;两个包括在下面:

1)

{
  "json" : {
    "harkUpdate" : {
      "more" : [
        {
          "unread-count" : {
            "last" : 1613507864973,
            "index" : {
              "graph" : {
                "graph" : "\/ship\/~dopzod\/urbit-help",
                "index" : "\/"
              }
            }
          }
        },
        {
          "seen-index" : {
            "index" : {
              "graph" : {
                "index" : "\/",
                "graph" : "\/ship\/~dopzod\/urbit-help"
              }
            },
            "time" : 1613507864973
          }
        }
      ]
    }
  },
  "response" : "diff",
  "id" : 3
}
    {
      "json" : {
        "graph-update" : {
          "keys" : [
            {
              "name" : "book-club-4717",
              "ship" : "sicdev-pilnup"
            },
            {
              "name" : "dm--locrev-finlys",
              "ship" : "haddef-sigwen"
            },
            {
              "name" : "smol-bibliotheca",
              "ship" : "dasfeb"
            },
            {
              "name" : "interface",
              "ship" : "bitpyx-dildus"
            },
            {
              "name" : "jobs-gigs",
              "ship" : "nibset-napwyn"
            },
            {
              "name" : "tlon-general",
              "ship" : "bolbex-fogdys"
            }
          ]
        }
      },
      "id" : 1,
      "response" : "diff"
    }

如您所见,它们都有 idresponsejson 字段 - 但它们中的实际 json 响应各不相同。

通常我会使用 quicktype.io 之类的东西生成类,或者使用许多 ObjectMapping 框架之一。我试图在精神上畅通无阻的是,所有这些 json 响应都有一个名为“json”的字段,它具有不同的结构。我试图找出我可以为给定这种结构的响应创建独特的类。任何帮助表示赞赏。

【问题讨论】:

  • 你可以把这 2 个 JSON 组合起来,让所有属性都是可选的
  • @aiwiguna 你是什么意思;都在一个班级?如果您写一个带有示例的答案,我会接受!
  • 你也可以像πter answer一样使用泛型

标签: ios json swift alamofire object-object-mapping


【解决方案1】:

您可以声明一个基本对象,其 json 属性将是符合 Codable 的泛型类型。

struct JSON<T : Codable>: Codable {
    let json: T
    let id: Int
    let response: String
}

在你定义了两个结构体之后,它们分别代表第一个和第二个 json 对象。为简单起见,我将只定义代表第二个 JSON 的对象:

struct GraphUpdate: Codable {
    let graphUpdate: Keys

    enum CodingKeys: String, CodingKey {
        case graphUpdate = "graph-update"
    }
}

struct Keys: Codable {
    let keys: [Key]
}

struct Key: Codable {
    let name, ship: String
}

并且在尝试解码时,您必须指定要解码的对象:

let item = try? JSONDecoder().decode(JSON<GraphUpdate>.self, from: data)

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 2015-06-27
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多