2016-12-02 131 views
0

我是Alamofire的新手,我測試了一些API。我遇到了匯率。所以JSON文件是這樣Alamofire 4.0 JSOn解析Swift

["base": CAD, "date": 2016-12-01, "rates": { 
AUD = "1.0097"; 
BGN = "1.3735"; 
BRL = "2.57"; 
CHF = "0.7559"; 
CNY = "5.1388"; 
CZK = "19.004"; 
DKK = "5.2248"; 
EUR = "0.70225"; 
GBP = "0.59058"; 
HKD = "5.7881"; 
HRK = "5.2985"; 
HUF = "220.48"; 
IDR = 10108; 
ILS = "2.8607"; 
INR = "51.009"; 
JPY = "85.246"; 
KRW = "871.9400000000001"; 
MXN = "15.403"; 
MYR = "3.331"; 
NOK = "6.2941"; 
NZD = "1.0539"; 
PHP = "37.102"; 
PLN = "3.1374"; 
RON = "3.1631"; 
RUB = "47.591"; 
SEK = "6.8775"; 
SGD = "1.0657"; 
THB = "26.616"; 
TRY = "2.6006"; 
USD = "0.7462800000000001"; 
ZAR = "10.504";}] 

typealias JSONStandard = [String: AnyObject] 

func parseData(JSONData:Data) { 
    do { 
     var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard 
     if let rates = readableJSON["rates"] as? JSONStandard{ 
      for i in 0..<rates.count { 
       let rate = rates[i] as! //Here 
      } 
      print(rates) 
     } 
     print(readableJSON) 

    } catch { 
     print(error) 
    } 
} 

我能得到側「差餉」,但我不明白我怎麼會解析裏面的「速率」中的所有數據。我以爲我必須把它保存在字典裏面。很迷茫謝謝

+0

這甚至不是一個有效的數據集。它不應該包含分號。 –

+0

@ElTomato這實際上是如此真實,我只是意識到這一點。但我確信有一種解決方法 –

+0

沒有辦法繞過它。您當然可以手動修復您的JSON數據集並將其作爲Swift文件讀取。 –

回答

0

正如你可以看到它在字符串的雙重價值,所以你需要AnyObject先轉換爲字符串,然後將其轉換爲雙。你可以像下面這樣做(在斯威夫特操場測試):

import Foundation 

typealias JSONStandard = [String: AnyObject] 

func parseData(JSONData:Data) { 
    do { 
     guard let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as? JSONStandard, 
      let ratesJSON = readableJSON["rates"] as? JSONStandard 
      else { return } 
     print("Readable JSON :") 
     print(readableJSON) 
     let rates = ratesJSON.flatMap({ (key, value) -> ([String: Double]) in 
      guard let value = value as? String, let convertedValue = Double(value) else { return [:] } 
      return [key: convertedValue] 
     }) 
     print("Rates :") 
     print(rates) 

    } catch { 
     print(error) 
    } 
} 

let jsonString = "{\"base\": \"CAD\", \"date\": \"2016-12-01\", \"rates\": { \"AUD\": \"1.0097\", \"BGN\": \"1.3735\", \"BRL\": \"2.57\"}}" 
let jsonData = jsonString.data(using: String.Encoding.utf8)! 
parseData(JSONData: jsonData) 

結果:

Readable JSON : 
["base": CAD, "date": 2016-12-01, "rates": { 
    AUD = "1.0097"; 
    BGN = "1.3735"; 
    BRL = "2.57"; 
}] 
Rates : 
[("BGN", 1.3734999999999999), ("AUD", 1.0097), ("BRL", 2.5699999999999998)] 
+0

是否有可能告訴我詳細的用法守衛? –

+0

@ J.Kim1205警衛就像一個if,但它只會檢查條件是否爲真,它也被稱爲保鏢模式。所以它會像這樣的警戒條件工作其他{/ /你的代碼和返回},如果條件爲真,它會去下一行,如果沒有它會去其他塊這裏也有一個很好的解釋 - > http ://ericcerney.com/swift-guard-statement/ –

+0

jsonString.data?這是從 –

0

你必須把它保存到雙數組:

var yourArray = [Double]() 

    for i in 0..<rates.count { 
     let rate = rates[i] as! Double 
     print(rate) 
     yourArray.append(rate) 
    } 

print(yourArray.description) 
+0

,這意味着生病只能保存我的雙重價值,我也想保存我的字符串 –