ios – JSON写入中的顶级类型无效’

我将一些参数传递给api,完成添加到购物车功能.但是当我传递参数时,它显示崩溃 JSON中的无效顶级类型写’我知道我的传递参数中存在问题.请帮帮我!.怎么做.请帮帮我!!!

这是我传递的参数的json格式!!:

{
    "cartType" : "1","cartDetails" : {
        "customerID" : "u","cartAmount" : "6999","cartShipping" : "1","cartTax1" : "69","cartTax2" : "","cartTax3" : "","cartCouponCode" : "","cartCouponAmount" : "","cartPaymentMethod" : "","cartProductItems" : {
            "productID" : "9","productPrice" : "6999","productQuantity" : "1"
        }
    }
}

我更新的解决方

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","cartProductItems" : [
                "productID" : "9","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....")
                            if (json["CartID"] as? Int?) != nil
                            {
                                dispatchQueue.main.async(execute: {

                                    print("INSIDE CATEGORIES")
                                    self.addtocartdata.append(Addtocartmodel(json:CartID))


                                })
                            }

                        }

                    }
                })

            }
        })

        dataTask.resume()
    }
}

附加值的最后一个问题:

在我的模型中,数据类看起来像这样:

class Addtocartmodel

{
 var cartid : Int?
init(json:NSDictionary)
    {
         self.cartid = json["CartID"] as? Int
}
}

解决方法

你的json有一些错误的格式.在swift中使用字典比json清楚得多,并使用JSONSerialization将字典转换为json字符串.

代码如下所示:

func addtocartapicalling ()
{
    let headers = [
        "cache-control": "no-cache",error) -> Void in
            if (error != nil) {
                print(error)
            } else {

                dispatchQueue.main.async(execute: {

                    if let json = (try? JSONSerialization.jsonObject(with: data!,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()
    }
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...