我正在尝试在Swift中解码嵌套对象的数组,但无法正常工作。嵌套对象的类型与我使用Realm存储值的类型相同,如下所示:
struct myObject: Codable {
var name: String?
let otherObjects = List<myObject>()
var events: [String]?
...
if let objects = try container.decodeIfPresent([myObject].self, forKey: .otherObjects) {
otherObjects.append(objectsIn: objects)
}
}
解码器功能-此功能适用于顶级对象中的所有其他字段,包括事件(它是String的数组)。
static func decodeResponse<T:Codable>(_ response : Any?) -> T? {
if let response = response, let dict = response as? [String:Any] {
var dictionaryToParse = dict
var arrayToParse: [[String:Any]]?
if let dataObject = dict["data"] as? [String:Any] {
//sometimes the response has an outer "data" OBJECT
dictionaryToParse = dataObject
} else if let dataArray = dict["data"] as? [[String:Any]] {
//sometimes the response has an outer "data" ARRAY
arrayToParse = dataArray
}
do {
guard let data = try? JSONSerialization.data(withJSONObject: arrayToParse ?? dictionaryToParse, options: []) else { return nil }
let obj = try JSONDecoder().decode(T.self, from: data)
print("DECODE: \(obj)")
return obj
}
catch let error {
print("ERROR: (decodeResponse): \(error)")
return nil
}
}
return nil
}
编码键映射为相同类型,因此不会输出任何错误。