[英]Getting array of objects from CodableAlamofire
Im using Alamofire with the CodableAlamofire extension but I having trouble in get one data in my json response. 我将Alamofire与CodableAlamofire扩展一起使用,但在json响应中获取一个数据时遇到了麻烦。
This is my json: 这是我的json:
{
"total": 95,
"per_page": 100,
"current_page": 1,
"last_page": 1,
"from": 1,
"to": 95,
"data": [
{
"id": 1,
"name": "ONE",
"city": "CITY 1"
},
{
"id": 2,
"name": "TWO",
"city": "CITY 2"
},
{
"id": 3,
"name": "THREE",
"city": "CITY 3"
}
]
}
I have these structs: 我有这些结构:
struct AssetResult: Decodable {
let current_page : Int
// let data : [AssetData]
let from : Int
let last_page : Int
let per_page : Int
let to : Int
let total : Int
enum CodingKeys : String, CodingKey {
case current_page
// case data
case from
case last_page
case per_page
case to
case total
}
}
struct AssetData: Decodable {
let city : String
let id : String
let name : String
}
And this is the code to get the data in AssetResult
struct: 这是在AssetResult
结构中获取数据的代码:
let parameters: Parameters = ["page": 1]
let url = URL(string: "http://url")!
let decoder = JSONDecoder()
Alamofire.request(url, parameters: parameters).responseDecodableObject(keyPath: nil, decoder: decoder) { (response: DataResponse<AssetResult>) in
let repo = response.result.value
print(repo)
}
The problem is everytime I try to get the data
(uncommenting the data
in the AssetResult
struct) the print(repo)
turn to nil
. 问题是每次我尝试获取data
(取消注释AssetResult
结构中的data
)时, print(repo)
变为nil
。
If I let the data
commented this is printed: 如果我让data
注释,则将其打印出来:
Optional(AssetResult(current_page: 1, from: 1, last_page: 1, per_page: 100, to: 95, total: 95))
How can I get the array of objects? 如何获得对象数组? Preferably as an array of AssetData objects. 最好作为AssetData对象的数组。
Thanks 谢谢
I ran several tests with the JSON return and realized that some assets appeared without a city, which caused the error: 我使用JSON返回值运行了一些测试,并发现有些资产没有城市出现,这导致了错误:
{
"id": 10,
"name": "TEN",
"city": null
},
So I just needed change the city to optional, adding the ?
所以我只需要将城市更改为可选城市,并添加?
after the type: 类型之后:
struct AssetData: Decodable {
let city : String?
let id : String
let name : String
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.