使用 api 调用发送 JSON 数组并存储在数据库中

Send JSON Array and store in database using api calls

我想按以下格式通过 Post 方法发送一个 json 对象

[
    {
        "product_id": 8,
        "quantity": 2
    },
    {
        "product_id": 19,
        "quantity": 1,
        "variations": {
            "pa_size": "XL"
        }
    }
]

并将此 JSON 存储在 sql 数据库中 按照以下格式

这是我的代码:

//i get the products id and quantity

 for var i=0; i<ct ; i++ {
   let   paramsArray = [["product_id":  (prId[i]), "quantity" :   (productQty["\(prId[i])"]!)]]

//converting array to json using SwiftyJSON

 let paramsJSON = JSON(paramsArray)
 let paramsString = paramsJSON.rawString(NSUTF8StringEncoding, options: [])

 //appending products to array

   cartProducts.append(paramsString!)
       }
   //printing array products
      print("cartPro:\(cartProducts)")

数组的打印输出是这样的我也尝试删除反斜杠

cartPro:["[{\"product_id\":19,\"quantity\":1}]", "[{\"product_id\":8,\"quantity\":1}]"]

我想这样输出,这样我就可以使用 api:

通过 post 方法发送
[{"product_id":19,"quantity":1}, {"product_id":8,"quantity":1}]

有没有其他方法可以将 JSON 对象附加到数组并发送?还是我做错了?

请帮帮我

确保您的 cartProducts 是 AnyObject 类型。

将 cartProducts 声明为任何对象

var cartProducts = [String]() 

改为

var  cartProducts =[AnyObject]()

并尝试追加,应该可以。

附加输出后,您将在控制台日志中得到类似的内容

cartPro:[{"product_id":19,"quantity":1}, {"product_id":8,"quantity":1}]

你可以通过 api 发送那个变量。