问题描述】:
我的应用从我们的服务器接收二进制数据。在我的旧 Objective-C 代码中,我按如下方式处理响应数据:
- 使用 NSJSONSerialization 将 NSData 转换为 NSDictionary,其中包含如下数据:{"code": "0", "info": {"user_id": 123456}},
- 编写一个 MTLModel 子类
- 使用 Mantle API 将上述 info 字典,即 {"user_id": 123456} 转换为我的模型
现在我想用 Swift 来做这件事,我刚刚了解了 Codable 协议的便利性。但是,看起来这个协议实现了,我只能用Data/NSData转换,这使得上面的程序变成了这样:
- 同上
- 编写符合 Codable 协议的结构/类
- 使用 NSJSONSerialization 将 info 字典,即 {"user_id": 123456} 重新编码为 Data/NSData
- 使用 JSONDecoder 将此数据解码到我的模型中
所以我的问题是,可以直接从字典中派生 Codable 对象吗?
编辑:
感谢你们的回答,但让我澄清一下。 虽然响应 JSON 格式有些固定,但是请求和响应有很多不同,所以 info 部分是不同的。例如:
- R1: {"code": "0", "info": {"user_id": 123456}} 是用户 ID 请求的响应
- R2: {"code": "0", "info": {"temperature": 20, "country": "London"}} 是天气温度请求的响应
因此,Codable 类/结构应该仅从 info 部分构造,而不是整个响应数据,这就是为什么我不能简单地应用步骤2 & 4 来实现这一点。
【问题讨论】:
- 如果我理解正确,您可以在步骤 1 中直接解码。
let result = try JSONDecoder().decode(SomeClass.self, from: data)
其中SomeClass
是您的自定义类,“data”是您从服务器接收的数据
【解决方案1】:
您的 JSON 看起来像这样:
<code>let r1 = Data("""
{"code": "0", "info": {"user_id": 123456}}
""".utf8)
let r2 = Data("""
{"code": "0", "info": {"temperature": 20, "country": "London"}}
""".utf8)
code>
以及看起来像这样的“信息”类型:
struct UserID: Codable {
var userId: Int
}
struct WeatherTemperature: Codable {
var temperature: Int
var country: String
}
我假设一个解码器会进行蛇形大小写转换(您可以通过实现 CodingKeys 或其他方式来替换它):
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
鉴于此,您需要一个通用的响应类型:
<code>struct Response<Info: Codable>: Codable {
var code: String
var info: Info
}
code>
这样,您可以直接从 JSON 对象解码您的响应:
let userID = try decoder.decode(Response<UserID>.self, from: r1).info
let weather = try decoder.decode(Response<WeatherTemperature>.self, from: r2).info
【讨论】:
- 谢谢!我以为它可以通过Generic解决,但我只是不知道它的语法。
【解决方案2】:
将 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)
}
【讨论】:
【解决方案3】:
不,不是直接的,是的,有点。使困惑?我会解释的。
Codable
用于与Data
进行编码/解码,JSON 是当今最流行的编码,但您也可以使用 plist 或编写自己的自定义编码器/解码器。
但坚持使用标准编码器,如果您想从 Dictionary
转换为符合 Codable
的类型,您可以通过将 Dictionary
编码为 JSON(或 plist)然后解码结果Data
到 Codable
的东西......这基本上就是你描述的过程。注意如果Dictionary
的key和value类型都是Codable
(比如[String: Int]
),可以用JSONEncoder/Decoder代替JSONSerialization
。但是,例如,如果是 [String: Any]
,则需要使用 JSONSerialization
,因为 Any
不符合 Codable
。
话虽如此,您可以扩展Codable
以包含一个采用Dictionary
的可失败或抛出初始值设定项,在其中您将字典编码为Data
,然后使用JSONDecoder
进行解码。这仍然是您已经在执行的过程,除了 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
,而是扩展您的模型。
【讨论】:
【解决方案4】:
<code> {
"code": "0",
"info": {
"user_id": 123456
}
}
code>
因此,如上所述,只要您的结构匹配,您就可以一步完成。
例如:
<code> struct ServerResponse: Codable {
var code: Int
var info: [String:Int]
}
code>
或者:
<code>struct ServerResponse: Codable {
var code: Int
var info: Info
}
struct Info: Codable {
var user_id: Int
}
code>
那么简单
let serverResponse = try? JSONDecoder().decode(ServerResponse.self, from: your_server_json_data)