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

O-mkar
  • 5,430
  • 8
  • 37
  • 61
Aadit33
  • 192
  • 10
  • 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](http://stackoverflow.com/questions/10117031/escape-quotes-in-objective-c?answertab=oldest#tab-top). – Armands L. Nov 23 '15 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. – henrikstroem Nov 23 '15 at 12:13
  • Try this solution: http://stackoverflow.com/questions/26857881/is-there-any-way-to-fix-a-json-response/26860779#26860779 – Kampai Nov 23 '15 at 13:08

1 Answers1

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.

O-mkar
  • 5,430
  • 8
  • 37
  • 61