我正在使用Alamofire和CodableAlamofire扩展,但我在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"
}
]
}
我有这些结构:
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
}
这是在AssetResult
struct:
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)
}
每当我尝试data
(取消注释data
结构中的AssetResult
)print(repo)
转向nil
时,问题就出现了。
如果我打印了data
,则会打印出来:
Optional(AssetResult(current_page: 1, from: 1, last_page: 1, per_page: 100, to: 95, total: 95))
如何获取对象数组?最好是作为AssetData对象的数组。
由于
答案 0 :(得分:0)
我在JSON返回时运行了几次测试,发现有些资产没有城市,导致错误:
{
"id": 10,
"name": "TEN",
"city": null
},
所以我只需要将城市更改为可选,在类型后添加?
:
struct AssetData: Decodable {
let city : String?
let id : String
let name : String
}