在 api swift Codable 和模型数据中获得位置
get position in a api swift Codable and Model data
我正在从这样的 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 协议错误
我正在使用
let resP = try JSONSerialization.jsonObject(with: data, options: .init()) as? [String: AnyObject]
print("resP", )
在我的 Service/Network
脚本中
谢谢有人知道
您不能在 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)
}
我正在从这样的 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 协议错误
我正在使用
let resP = try JSONSerialization.jsonObject(with: data, options: .init()) as? [String: AnyObject]
print("resP", )
在我的 Service/Network
脚本中谢谢有人知道
您不能在 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)
}