【问题标题】:Issue parsing the json response in swift快速解析 json 响应的问题
【发布时间】: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 根对象无疑是一个数组。

标签: json swift alamofire


【解决方案1】:

我认为这里最好的方法是使用Decodable 协议。

struct Item: Decodable {
    var itemId: Int
    var sku: String
    // ...
}

然后使用responseDecodable(_:)方法


// create a decoder to handle the `snakeCase` to `camelCase` attributes
// thanks to this `Decoder`, you are able to add a property `var itemId: Int` instead of `var item_id: Int`
let decoder: JSONDecoder = {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    return decoder
}()

AF.request("https://adamas-intl.com/rest/V1/carts/mine/items")
  .validate()
  .responseDecodable(of: [Item].self, decoder: decoder) { (response) in
    guard let items = response.value else { return }
    // do what you want
  }

【讨论】:

    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2023-03-23
    • 2020-02-22
    • 1970-01-01
    • 2014-10-14
    相关资源
    最近更新 更多