0

I want to send a json object through Post method in this following format

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

and store this JSON in sql database in following format POST MAN SNAP

here is my code:

//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)")

printed output of array comes like this i also tried to remove backslash

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

i want out put like this so i can send through post method using api:

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

is there any other way i can append JSON objects to array and send? or i'm doing it wrong?

please help me

3
  • You should search before posting questions. They are called escape characters - Special Characters like Quotes, slashes and others require ` \` to make that character to remove its special functionality. Took this answer from here. Commented Nov 23, 2015 at 11:59
  • 1
    Your array is not what you think it is. It only holds one value, a string, and because this string has quotes in it, they have been escaped. You need to look into how you're constructing the array: you can't build an array inside a for loop this way, it will only hold last item. Commented Nov 23, 2015 at 12:13
  • Try this solution: stackoverflow.com/questions/26857881/… Commented Nov 23, 2015 at 13:08

1 Answer 1

1

Make sure your cartProducts is of of type AnyObject.

declare cartProducts as any object

var cartProducts = [String]() 

change it to

var  cartProducts =[AnyObject]()

and try appending and it should work.

after appending the out put you will get something like this in your console log

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

than you can send that variable through your api.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.