2017-09-06 30 views
0

我們使用firebase作爲後端。我們是從火力得到的迴應是:將JSON轉換爲Swift3中所需的數組格式

{ 
    "2_3" =  { 
     OTI = 80; 
     OTIP = 70; 
     SPR2 = 40; 
    }; 
    "2_5" =  { 
     OTI = 60; 
     OTIP = 70; 
     SPR2 = 30; 
     SPR3 = 40; 
    }; 
    "2_8" =  { 
     OTI = 20; 
    }; 
} 

我們要的是:

["2_8": ["OTI": "20"], "2_3": ["SPR2": "40", "OTI": "80", "OTIP": "70"], "2_5": ["SPR2": "30", "SPR3": "40", "OTI": "60", "OTIP": "70"]] 

如何Swift3實現這一目標?另外,我們能否以上述格式獲得Firebase的迴應?

+0

你不想要的值作爲整數? –

+0

這些都只是不同的打印格式(除了在第二種格式中,數字是字符串而不是整數)。所以請給你更多關於你想要實現的內容。 –

+0

首先沒有涉及陣列。所有集合類型都是字典。其次,最有可能的結果就是你想要的格式。 'print'以* objective-cish *字典表示形式顯示對象。 – vadian

回答

0

這裏有一個解決方案;它非常詳細,可以大大縮短。我添加了評論,以便您更輕鬆地遵循邏輯。

還有一些其他解決方案。

var dataArray = [ [String: Any] ]() 

let numbersRef = self.ref.child("numbers") //assume the parent node is called numbers 
numbersRef.observeSingleEvent(of: .value, with: { snapshot in 
    for child in snapshot.children { //iterate over each child in numbers 
     let snap = child as! DataSnapshot //use the child as a snapshot 
     let key = snap.key //get it's key ie. 2_3, 2_5 etc 
     let value = snap.value as! [String: Any] //get it's children as a dictionary, looses ordering 

     let dict = [key: value] //create a dictionary of key: value 
     dataArray.append(dict) //store it 
    } 

    //to test 
    for element in dataArray { //for each element in the dataArray 
     for keyValuePair in element { //each element is a key:value pair 
      let key = keyValuePair.key //get the key 
      let value = keyValuePair.value //get the value 
      print(key, value) 
     } 
    } 
}) 

和輸出(我只用前兩個節點)

2_3 ["SPR2": 40, "OTI": 80, "OTIP": 70] 
2_5 ["SPR2": 30, "SPR3": 40, "OTI": 60, "OTIP": 70] 

這裏是一個濃縮版

var dataArray = [ [String: Any] ]() 

let numbersRef = self.ref.child("numbers") //assume the parent node is called numbers 
numbersRef.observeSingleEvent(of: .value, with: { snapshot in 
    for child in snapshot.children { //iterate over each child in numbers 
     let snap = child as! DataSnapshot //tell the child it's a snapshot 
     dataArray.append([snap.key: snap.value as! [String: Any]]) 
    } 
})