我需要获取整个字典作为键“内容”的字符串。我将它作为 nil 接收。我尝试使用 [String:Any] 抛出异常,无法确认任何可解码
public static func getModelObjects<R: Codable>(_ type: R.Type, from data: Any?) -> [T]? {
var mappedObjects: [T]?
if let dataAsDic = data as? JSONDictionary {
let decodedObject = decodableData(type, dictionaryData: dataAsDic)
mappedObjects = [decodedObject] as? [T]
} else if let dataAsArray = data as? [JSONDictionary] {
var objects: [R] = []
for dataAsDic in dataAsArray {
guard let decodedObject = decodableData(type, dictionaryData: dataAsDic) else {
return nil
}
objects.append(decodedObject)
}
mappedObjects = objects as? [T]
}
return mappedObjects
}
private static func decodableData<R: Codable>(_ type: R.Type, dictionaryData: JSONDictionary) -> R? {
let decoder = JSONDecoder()
do {
let jsonData = try JSONSerialization.data(withJSONObject: dictionaryData, options: JSONSerialization.WritingOptions.prettyPrinted)
let decodedData = try decoder.decode(type, from: jsonData)
return decodedData
} catch {
return nil
}
}
public class Configuration: CacheableEntity, ConfigurationStorageProtocol, Codable {
public dynamic var configurationID: String!
/// Version of configuration
public dynamic var version: String!
private var storedConfigDict: JSONDictionary?
private var storedConfigData: Data?
// Holds complete configuration as string
dynamic var configString: String?
/// Codable keys to confirm Codable protocol
private enum CodingKeys: String, CodingKey {
case configurationID = "id"
case version
case name
case content
}
public required init(from decoder: Decoder) throws {
super.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try? container.decode(String.self, forKey: .name)
self.configurationID = try? container.decode(String.self, forKey: .configurationID)
self.version = try? container.decode(String.self, forKey: .version)
self.configString = try? container.decode(String.self, forKey: .content)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try? container.encode(configurationID, forKey: .configurationID)
try? container.encode(version, forKey: .version)
try? container.encode(name, forKey: .name)
}
}
在下面的 json 中,我需要将整个内容作为字符串获取。我尝试过使用 [String:Any] 但它崩溃了,因为它提到任何不能符合可解码。
"name": "sdkconfig",
"id": "gma_5.0_ios_sdkconfig_1.0_us",
"version": "1.0",
"modifiedDateTime": "2017-06-15T08:15:25.304Z",
"content": {
"configName": "sdkConfig",
"configVersion": "1.0",
"enabled": {
"modules": [
"account",
"nutrition",
"restaurant",
"offer",
"ordering",
"favorite"
],
"socialAccounts": [
"facebook",
"google",
"twitter"
]
}
}