如何在 Swift 中直接将 Dictionary 转换为 Codable 实例?

How to directly convert a Dictionary to a Codable instance in Swift?

我的应用程序从我们的服务器接收二进制数据。在我的旧 Objective-C 代码中,我按如下方式处理响应数据:

  1. 使用NSJSON序列化将NSData转换为NSDictionary,其中包含的数据如下:{"code": "0", "info": {"user_id": 123456}},
  2. 写一个MTLModel子类
  3. 使用 Mantle API 将上面的 info 字典,即 {"user_id": 123456} 转换成我的模型

现在我想用 Swift 来做这个,我刚刚了解到 Codable 协议是多么方便。但是,看起来实现了这个协议,我只能用Data/NSData转换它,这使得上面的过程变成了这样:

  1. 同上
  2. 写一个struct/class符合Codable协议
  3. 使用NSJSON序列化将info字典,即{"user_id": 123456},再次编码为Data/NSData
  4. 使用JSON解码器将此数据解码到我的模型中

所以我的问题是,Codable 对象是否可以直接从字典派生?

编辑:

感谢你们的回答,但让我澄清一下。 虽然响应的JSON格式有些固定,但是有很多不同的请求和响应,所以info部分是不同的。例如:

因此,Codable class/struct 应该仅由 info 部分构建,而不是整个响应数据,这就是为什么我不能简单地应用步骤 2 和 4 来完成它。

将json字符串转换为数据,然后使用json解码器

转换为可编码结构
let json = "{\"CustomerTypeID\":3,\"CustomerID\":4330,\"CustomerName\":\"Black :)\",\"CustomerTypeName\":\"Member\",\"IsWalkedInCustomer\":false,\"Email\":\"black@yopmail.com\",\"Mobile\":\"+447400369852\",\"AllowPartPaymentOnCore\":true,\"ServiceBookingList\":[{\"SaleStatusTypeID\":2,\"SaleStatusTypeName\":\"Paid\",\"ServiceName\":\"Nail Polish Service\",\"BookingStatusTypeID\":1,\"BookingStatusTypeName\":\"Booked\",\"SaleID\":71861,\"ID\":83756,\"ServiceCategoryID\":85,\"ServiceID\":173,\"ServicePackageID\":245,\"Price\":0.00,\"TotalPrice\":0.00,\"CleaningTimeInMinute\":10,\"StartDate\":\"2021-06-30T00:00:00Z\",\"StartTime\":\"11:00:00\",\"EndTime\":\"11:30:00\",\"AssignedToStaffID\":268,\"FacilityID\":0,\"Description\":\"\",\"IsPartialPaid\":false,\"TotalAmountPaid\":0.0,\"SaleRefundAmount\":0.00,\"AssignedToStaffName\":\"Iqra Rasheed\",\"CustomerMembershipID\":null,\"Duration\":\"00:30\",\"LastUpdatedByName\":\"Iqra Rasheed\",\"FacilityName\":\"\",\"StaffImagePath\":\"Staff_fabf1c3a-e2bf-45c6-b7f1-3cddd17fb358.jpg\",\"TotalTaxPercentage\":22.00,\"TotalDiscountAmount\":0.00,\"IsFree\":false,\"HasUnSubmittedForm\":true,\"HasAtleastOneMandatoryForm\":true}]}"
        
let data = json.data(using: .utf8)
        
let decoder = JSONDecoder()
        
if let data = data, let model = try? decoder.decode(YourCodableModel.self, from: data) {
    print(model)
}

不,不直接,是的,有点。使困惑?我会解释。

Codable 意味着 encode/decode to/from Data,JSON 是当今最流行的编码,但您也可以使用 plist 或编写您自己的自定义 encoder/decoder.

但是坚持使用标准编码器,如果您想从 Dictionary 转换为符合 Codable 的类型,您可以通过将 Dictionary 编码为 JSON (或 plist),然后将结果 Data 解码为 Codable 东西......这基本上就是你描述的过程。请注意,如果 Dictionary 的键和值类型都是 Codable(例如 [String: Int]),则可以使用 JSONEncoder/Decoder 而不是 JSONSerialization。但是,例如,如果是 [String: Any],您需要继续使用 JSONSerialization,因为 Any 不符合 Codable

话虽如此,您可以扩展 Codable 以包含采用 Dictionary 的可失败或抛出初始化程序,您可以在其中将字典编码为 Data,然后使用 [= 进行解码29=]。这仍然是您已经在做的过程,只是 Codable 的任何内容都会自动提供以方便使用。

extension Codable
{
    init<Key: Hashable, Value>(_ dict: [Key: Value]) throws where Key: Codable, Value: Codable
    {
        let data = try JSONEncoder().encode(dict)
        self = try JSONDecoder().decode(Self.self, from: data)
    }
}

但这听起来并不像您实际上需要 任何 可编码的东西来从 Dictionary 初始化,只是您的模型。在这种情况下,与其扩展 Codable,不如扩展您的模型。

 {
  "code": "0",
  "info": {
           "user_id": 123456
          }
 }

所以如上所述,只要您的结构匹配,您就可以一步完成。

例如:

 struct ServerResponse: Codable {
      var code: Int
      var info: [String:Int]
 }

或者:

struct ServerResponse: Codable {
      var code: Int
      var info: Info
}

struct Info: Codable {
     var user_id: Int
}

那么简单

 let serverResponse = try? JSONDecoder().decode(ServerResponse.self, from: your_server_json_data)

您的 JSON 看起来像这样:

let r1 = Data("""
{"code": "0", "info": {"user_id": 123456}}
""".utf8)

let r2 = Data("""
{"code": "0", "info": {"temperature": 20, "country": "London"}}
""".utf8)

“信息”类型如下所示:

struct UserID: Codable {
    var userId: Int
}

struct WeatherTemperature: Codable {
    var temperature: Int
    var country: String
}

我假设一个解码器进行 snakeCase 转换(您可以通过实现 CodingKeys 或其他方式来替换它):

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

鉴于此,您需要一个通用的响应类型:

struct Response<Info: Codable>: Codable {
    var code: String
    var info: Info
}

然后,您可以直接从 JSON 对象解码您的响应:

let userID = try decoder.decode(Response<UserID>.self, from: r1).info
let weather = try decoder.decode(Response<WeatherTemperature>.self, from: r2).info