2015-05-21 27 views
2

我在使用Swift在JSON中創建特定結構時遇到問題。我使用Swifty JSON進行解析,但我無法弄清楚如何創建一個。在Swift中創建特定的JSON結構

我有這個數組,它由產品的Id和數量Ints填充到購物籃中。我需要將數組放入我的JSON中,但我不知道如何。

如果你能幫助我,我會很高興:)

var productArray = Array<(id: Int,quantity: Int)>() 

    let jsonObject: [String: AnyObject] = [ 
     "order": 1, 
     "client" : 1, 
     "plats": [ 
      for product in productArray 
      { 
      "id": product.id 
      "quantity": product.quantity 
      } 
     ] 
    ] 
+0

此代碼是否正在編譯? – Blackus

+0

不行,只是「在容器文字預期的表達式」在行,我不知道如何做到這一點 – Dinosan0908

+1

你有'for'循環'''''''',這是絕對不允許的。你想要他們'平臺'鑰匙的價值是什麼? – ABakerSmith

回答

1

你不能只是在定義你的字典時循環遍歷東西。這是另一種方法。

首先,創建數組:

var productArray = Array<(id: Int,quantity: Int)>() 

添加一些產品(用於測試):

productArray += [(123, 1000)] 
productArray += [(456, 50)] 

地圖這個數組字典的一個新的數組:

let productDictArray = productArray.map { (product) -> [String : Int] in 
    [ 
     "id": product.id, 
     "quantity": product.quantity 
    ] 
} 

使用在您的JSON對象中新映射的數組:

let jsonObject: [String: AnyObject] = [ 
    "order": 1, 
    "client" : 1, 
    "plats": productDictArray 
] 
+0

裏面的一個數組謝謝你們,讓它震撼吧! :)有一個美好的一天傢伙:) – Dinosan0908

1

你不應該做任何類型的循環/條件使代碼塊,同時創造Array的或Dictionary的。爲此,您需要在外部執行該代碼段,創建一個變量並使用它。

請嘗試這種方式。

var productArray = Array<(id: Int,quantity: Int)>() 

    var prods = [[String:Int]]() 
    for product in productArray 
    { 
     var eachDict = [String:Int]() 
     eachDict["id"] = product.id 
     eachDict["quantity"] = product.quantity 
     prods.append(eachDict) 
    } 

    let jsonObject: [String: AnyObject] = [ 
     "order": 1, 
     "client" : 1, 
     "plats": prods 
    ]