使用 Codable 解析 Swift 中的字典数组

Parsing Array of dictionaries in Swift using Codable

我有一个来自 API 的 JSON 响应,但我无法弄清楚如何使用 Swift Codable 将其转换为用户对象(单个用户)。这是 JSON(为便于阅读删除了一些元素):

{
  "user": [
    {
      "key": "id",
      "value": "093"
    },
    {
      "key": "name",
      "value": "DEV"
    },
    {
      "key": "city",
      "value": "LG"
    },
    {
      "key": "country",
      "value": "IN"
    },
    {
      "key": "group",
      "value": "OPRR"
    }
  ]
}

你可以试试这样的结构

struct Model: Codable {
    struct User: Codable {
        let key: String
        let value: String
    }
    let singleuser: [User]
}

创建一个包含 2 个变量键和值的结构

public struct UserModel: Codable {
    public struct User: Codable {
        public let key: String
        public let value: String
    }
    public let user: [User]
}

之后使用 JSONDecoder 解码您的字符串。

func decode(payload: String) {
    do {
        let template = try JSONDecoder().decode(UserModel.self, from: payload.data(using: .utf8)!)
    } catch {
       print(error)
    }
}

如果您愿意,可以分两步完成。首先为接收到的 json

声明一个结构
struct KeyValue: Decodable {
    let key: String
    let value: String
}

然后解码 json 并使用 key/value 对将结果映射到字典中。

do {
    let result = try JSONDecoder().decode([String: [KeyValue]].self, from: data)

    if let array = result["user"] {
        let dict = array.reduce(into: [:]) { [=11=][.key] = .value}

然后使用 User

的结构将此字典编码为 json 并再次编码回来
struct User: Decodable {
    let id: String
    let name: String
    let group: String
    let city: String
    let country: String
}

let userData = try JSONEncoder().encode(dict)
let user = try JSONDecoder().decode(User.self, from: userData)

整个代码块变成

do {
    let decoder = JSONDecoder()
    let result = try decoder.decode([String: [KeyValue]].self, from: data)

    if let array = result["user"] {
        let dict = array.reduce(into: [:]) { [=13=][.key] = .value}
        let userData = try JSONEncoder().encode(dict)
        let user = try decoder.decode(User.self, from: userData)
        //...
    }
} catch {
    print(error)
}

有点麻烦,但不需要手动 key/property 匹配。