在 swift 中解析 json 响应的问题

问题描述 投票:0回答:2

我有一个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响应?

json swift alamofire
2个回答
3
投票

我认为,这里最好的方法是用一个 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
  }
© www.soinside.com 2019 - 2024. All rights reserved.