我的应用程序使用返回 JSON 的服务器,如下所示:
{
"result":"OK",
"data":{
// Common to all URLs
"user": {
"name":"John Smith" // ETC...
},
// Different for each URL
"data_for_this_url":0
}
}
如您所见,特定于 URL 的信息与通用字典存在于同一字典中user
。
目标:
- 将此 JSON 解码为类/结构。
- 因为
user
很常见,所以我希望它位于顶级类/结构中。
- 因为
- 编码为新格式(例如 plist)。
- 我需要保留原始结构。(即
data
从顶级user
信息和子对象的信息重新创建字典)
- 我需要保留原始结构。(即
问题:
重新编码数据时,我无法将user
字典(来自顶级对象)和特定于 URL 的数据(来自子对象)写入编码器。
要么user
覆盖其他数据,要么覆盖其他数据user
。我不知道如何将它们结合起来。
这是我到目前为止所拥有的:
// MARK: - Common User
struct User: Codable {
var name: String?
}
// MARK: - Abstract Response
struct ApiResponse<DataType: Codable>: Codable {
// MARK: Properties
var result: String
var user: User?
var data: DataType?
// MARK: Coding Keys
enum CodingKeys: String, CodingKey {
case result, data
}
enum DataDictKeys: String, CodingKey {
case user
}
// MARK: Decodable
init(from decoder: Decoder) throws {
let baseContainer = try decoder.container(keyedBy: CodingKeys.self)
self.result = try baseContainer.decode(String.self, forKey: .result)
self.data = try baseContainer.decodeIfPresent(DataType.self, forKey: .data)
let dataContainer = try baseContainer.nestedContainer(keyedBy: DataDictKeys.self, forKey: .data)
self.user = try dataContainer.decodeIfPresent(User.self, forKey: .user)
}
// MARK: Encodable
func encode(to encoder: Encoder) throws {
var baseContainer = encoder.container(keyedBy: CodingKeys.self)
try baseContainer.encode(self.result, forKey: .result)
// MARK: - PROBLEM!!
// This is overwritten
try baseContainer.encodeIfPresent(self.data, forKey: .data)
// This overwrites the previous statement
var dataContainer = baseContainer.nestedContainer(keyedBy: DataDictKeys.self, forKey: .data)
try dataContainer.encodeIfPresent(self.user, forKey: .user)
}
}
例子:
在下面的示例中,重新编码的 plist 不包含order_count
,因为它被包含 的字典覆盖user
。
// MARK: - Concrete Response
typealias OrderDataResponse = ApiResponse<OrderData>
struct OrderData: Codable {
var orderCount: Int = 0
enum CodingKeys: String, CodingKey {
case orderCount = "order_count"
}
}
let orderDataResponseJson = """
{
"result":"OK",
"data":{
"user":{
"name":"John"
},
"order_count":10
}
}
"""
// MARK: - Decode from JSON
let jsonData = orderDataResponseJson.data(using: .utf8)!
let response = try JSONDecoder().decode(OrderDataResponse.self, from: jsonData)
// MARK: - Encode to PropertyList
let plistEncoder = PropertyListEncoder()
plistEncoder.outputFormat = .xml
let plistData = try plistEncoder.encode(response)
let plistString = String(data: plistData, encoding: .utf8)!
print(plistString)
// 'order_count' is not included in 'data'!
/*
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>data</key>
<dict>
<key>user</key>
<dict>
<key>name</key>
<string>John</string>
</dict>
</dict>
<key>result</key>
<string>OK</string>
</dict>
</plist>
*/