我的 API 总是返回具有以下结构的 Json:
{
"data": Object
}
“对象”可以是原始数据(例如字符串)、另一个 Json 对象或 Json 数组。
{
"data": "string"
}
{
"data": {
"id_user": 1
"name": "name"
}
}
{
"data": [{
"id_user": 1
"name": "name"
},
{
"id_user": 2
"name": "name"
}]
}
如何访问“对象”以便使用 Codable 结构解析它?
最佳答案
好的,我找到了一个解决方案,使用字典。通过这种方式,我可以访问“数据”内容,将其转换为数据,然后使用 Codable 对其进行解析。这是代码:
let json = try JSONSerialization.jsonObject(with: response.data!, options: []) as! [String: Any]
guard let dataKey = json["data"] else {
throw CustomError.dataNotFound
}
let jsonData = try JSONSerialization.data(withJSONObject: dataKey, options: [])
let result = try JSONDecoder().decode(CodableStruct.self, from: jsonData)
希望对您有所帮助。
关于json - Swift 4 - 访问 Codable 结构的通用 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51020084/