【发布时间】:2020-05-22 12:55:48
【问题描述】:
我有一个json响应如下:
[
{
"item_id": 3310,
"sku": "BWBCL14KWGF003-BWBCL14KWGF003",
"qty": 1,
"name": "BWBCL14KWGF003",
"price": 471,
"product_type": "simple",
"quote_id": "4246",
"product_option": {
"extension_attributes": {
"custom_options": [
{
"option_id": "23243",
"option_value": "625080"
},
{
"option_id": "23242",
"option_value": "625032"
}
]
}
}
}
]
我有获取此响应的 alamofire 代码。
AF.request("https://adamas-intl.com/rest/V1/carts/mine/items", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success(let json):
if let res = json as? [[String: Any]]{
print("res is",res)
}
case let .failure(error):
print(error)
}
我需要从响应中获取 item_id 和其他值。这种获取方式,我无法到达值内部。 我该如何解析这个 json 响应?
【问题讨论】:
-
制作一个可编码的结构
-
您是否尝试过使用
if let res = json as? [String: Any]而不是if let res = json as? [[String: Any]],但我建议您使用Codable -
print(res.first?[“item_id”] as? Int) -
随着 Codable 协议的出现,Alamofire 已经不再需要了。如果您需要有关基于 Alamofire 的代码的帮助,请发布您遇到的代码。
-
@KevinMachado 根对象无疑是一个数组。