我正在从这样的 api 获取数据
[
{
"internData": {
"id": "abc123",
"name": "Doctor"
},
"author": "Will smith",
"description": "Is an actor",
"url": "https://www",
},
{
"internData": {
"id": "qwe900",
"name": "Constructor"
},
"author": "Edd Bett",
"description": "Is an Constructor",
"url": "https://www3",
}
]
我有这样的模型
struct PersonData: Codable {
let author: String?
let description: String?
let url: String?
}
但我不知道如何定义“internData”,我尝试使用另一个模型“InterData”并像 PersonData 一样定义 id 和名称,但我收到错误,我也尝试使用 [String:Any] 但我得到Codable 协议(protocol)错误
我正在使用
let resP = try JSONSerialization.jsonObject(with: data, options: .init()) as? [String: AnyObject]
print("resP", )
在我的服务/网络脚本中
如果有人知道,谢谢
最佳答案
在 Codable
的情况下,不能使用 [String:Any]
类型。您需要创建另一个 InternData
模型,供 PersonData
使用。
代码:
JSON 数据:
let jsonData =
"""
[
{
"internData": {
"id": "abc123",
"name": "Doctor"
},
"author": "Will smith",
"description": "Is an actor",
"url": "https://www",
},
{
"internData": {
"id": "qwe900",
"name": "Constructor"
},
"author": "Edd Bett",
"description": "Is an Constructor",
"url": "https://www3",
}
]
"""
//模型
struct PersonData: Codable {
let author: String?
let description: String?
let url: String?
let internData : InternData?
}
// New model
struct InternData : Codable {
let id : String?
let name : String?
}
//解析
do {
let parseRes = try JSONDecoder().decode([PersonData].self, from: Data(jsonData.utf8))
print(parseRes)
}
catch {
print(error)
}
关于ios - 获取 api swift 可编码和模型数据中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59015060/