【问题标题】:Getting value from Json dictionary in Swift 5从 Swift 5 中的 Json 字典中获取价值
【发布时间】:2020-10-13 23:43:11
【问题描述】:

我正在从在线货币服务中提取货币价值。

在获得所有货币的 json 数组后,我选择 2 种货币进行比较。

[{
    "symbol": "$",
    "name": "US Dollar",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD",
    "name_plural": "US dollars"
}, {
    "symbol": "CA$",
    "name": "Canadian Dollar",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "CAD",
    "name_plural": "Canadian dollars"
}]

我创建一个查询并将其发送回我的服务。

查询:

 let URLString: String =  finalURLPart1 + finalURLPart2 + finalURLPart3 + ""
        
        //print(#function, "URLString: ", URLString)
        
        var request = URLRequest(url: URL(string: URLString)!, timeoutInterval: Double.infinity)
        
        //print(#function, "request: ", request)
        request.httpMethod = "GET"

        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil {
                let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertController.Style.alert)
                let okButton = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
                alert.addAction(okButton)
                self.present(alert, animated: true, completion: nil)
            } else {
               
                // 2- Getting the response (Data)
                if data != nil {
                   
                    do {
                       
                    let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, Any>
                        //Async
                       
                        print(jsonResponse)
                        
                        DispatchQueue.main.async {
                          
                            if let rates = jsonResponse["rates"] as? [String : Any] {
                                
                               
                                
                                for convertedValue in rates.values {
                                    print("convertedValue: ", convertedValue)
                                    print("Type: ", type(of: convertedValue))
                                    
                                    
                                
                                }
                                
                                }
                            }
                            
                        
                        
                    } catch {
                        print("Error")
                    }
                    }
                
                
            }
        }
       
        // 3- Process the data (Parsing: or JSON Serialization)
        task.resume() // starting the task
        //semaphore.wait()
       
        
    }
    

我拿回来了:

["base": BAM, "date": 2020-10-13 22:18:00+00, "rates": {
    BDT = "51.11942821250704";
}]
for convertedValue in rates.values {
      print("convertedValue: ", convertedValue)
      print("Type: ", type(of: convertedValue))
}

输出是:

convertedValue:  51.11942821250704
Type:  __NSCFString

如何获得convertedValue的浮点值?

【问题讨论】:

  • 请编辑您的问题并发布收到的 JSON 字符串并正确格式化您的帖子
  • 会的。感谢格式化..
  • 返回的值不是有效的json

标签: arrays json swift dictionary


【解决方案1】:

如果我理解正确,您可以从rates JSON 对象中获取BDT 键的值,将其转换为它的类型(即String),然后使用@987654325 将其转换为Float @初始化器:

if let rates = jsonResponse["rates"] as? [String: Any] {
    if let stringValue = rates.values.first as? String, let convertedValue = Float.init(stringValue) {
        print("convertedValue:", convertedValue)
        print("Type:", type(of: convertedValue))
    }
}

这将打印:

convertedValue: 51.119427
Type: Float

【讨论】:

  • 感谢您的回答。 stringValue = rates["BDT"] 是个问题,因为每种货币都有自己的代码(例如“BDT”)
  • @ICT1901 如果rates 对象中始终只有一个键,则可以使用rates.values.first。我更新了我的答案。
猜你喜欢
  • 2016-05-09
  • 1970-01-01
  • 2018-07-08
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
相关资源
最近更新 更多