从json响应swift

时间:2019-08-14 08:42:40

标签: ios swift request alamofire nsjsonserialization

我正在使用Alamofire进行网址调用以获取数据,如下所示。

第一步,我将JSON数组转换为这种格式

  

[“ a”,“ b”,“ b”,“ c”]

及其正常工作。问题是_price变量

  

[“ 1233”,“ 1333”,“ 3422”,“ 2422”]

但是我需要从_price数组中删除双引号 最终_price像这样

  

[1233,1333,3422,2422]

class ChartVC: UIViewController {

    var _year : [String] = []
    var _month : [String] = []
    var _price : [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        getData()

    }

    func getData() {
        AF.request(DOLLAR_CHART).response { (response) in
            guard let data = response.data else { return }
            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
            if let items = responseJSON as? [[String: Any]] {
                var years: [String] = []
                var months: [String] = []
                var prices: [String] = []
                for item in items {
                    if let year =  item["year"] as? String  {
                        years.append(year)                            
                    }
                    if let month = item["month"] as? String {
                        months.append(month)
                    }
                    if let price = item["price"] as? String {
                        prices.append(price)
                    }

                }

                self._year = years
                self._month = months
                self._price = prices
                print(self._price)

                // show like this when print that["1233", "1333","3422","2422"]
                // how to show like this [1233, 1333, 3422, 2422]
                }
            } else {
                print("json is not array dictionary")
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

如果要从价格中获取整数值。

genepathways <- genepathways %>% mutate (Pathways = reorder_within (Pathways, -no_genes, Hallmark))

genepathwaysbp <- ggplot (genepathways)+
geom_col (mapping = aes (x = Pathways, y = no_genes, fill = Pathways))+
facet_wrap (~Hallmark, scales = "free")+
theme (legend.position = "none")+
theme (axis.text.x = element_blank ())+  #pathway names too long to fit, hence using plotly hover info to display this instead
scale_reordered_x()

(pp <- ggplotly (genepathwaysbp, tooltip = c("x", "y")))

并且您应该将_price和price数组定义为Int数组。

if let price = Int(item["price"] as? String ?? ""){
   prices.append(price)
 }