Invalid top-level type in JSON write'

前端 未结 2 826
日久生厌
日久生厌 2021-01-17 11:02

I am passing some parameter to api , to done add to cart function. But when i pass the parameter , it showing the crash Invalid top-level type in JSON write\' i

相关标签:
2条回答
  • 2021-01-17 11:32

    There is a subtle difference

    Try using this

    JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] 
    

    instead of

    JSONSerialization.data(withJSONObject: data, options: []) as? [String:AnyObject]
    
    0 讨论(0)
  • 2021-01-17 11:43

    Your json has some wrong format.Use a dictionary is much clear than json in swift, and use JSONSerialization to convert the dictionary to json string.

    The code looks like this:

    func addtocartapicalling ()
    {
        let headers = [
            "cache-control": "no-cache",
            "postman-token": "4c933910-0da0-b199-257b-28fb0b5a89ec"
        ]
    
        let jsonObj:Dictionary<String, Any> = [
            "cartType" : "1",
            "cartDetails" : [
                "customerID" : "sathish",
                "cartAmount" : "6999",
                "cartShipping" : "1",
                "cartTax1" : "69",
                "cartTax2" : "",
                "cartTax3" : "",
                "cartCouponCode" : "",
                "cartCouponAmount" : "",
                "cartPaymentMethod" : "",
                "cartProductItems" : [
                    "productID" : "9",
                    "productPrice" : "6999",
                    "productQuantity" : "1"
                ]
            ]
        ]
    
        if (!JSONSerialization.isValidJSONObject(jsonObj)) {
            print("is not a valid json object")
            return
        }
    
        if let postData = try? JSONSerialization.data(withJSONObject: jsonObj, options: JSONSerialization.WritingOptions.prettyPrinted) {
            let request = NSMutableURLRequest(url: NSURL(string: "http://expapi.php")! as URL,
                                              cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
            request.httpMethod = "POST"
            request.allHTTPHeaderFields = headers
            request.httpBody = postData
    
            let session = URLSession.shared
            let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
                if (error != nil) {
                    print(error)
                } else {
    
                    DispatchQueue.main.async(execute: {
    
                        if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? Dictionary<String,AnyObject>
                        {
                            let status = json["status"] as? Int;
                            if(status == 1)
                            {
                                print("SUCCESS....")
                                print(json)
                                if let CartID = json["CartID"] as? Int {
                                    DispatchQueue.main.async(execute: {
    
                                        print("INSIDE CATEGORIES")
                                        print("CartID:\(CartID)")
                                        self.addtocartdata.append(Addtocartmodel(json:json))
                                    })
                                }
                            }
                        }
                    })
                }
            })
    
            dataTask.resume()
        }
    }
    
    0 讨论(0)
提交回复
热议问题