JSON写入中的顶级类型无效'

时间:2016-10-23 05:51:14

标签: ios json swift

我将一些参数传递给api,完成添加到购物车功能。但是当我传递参数时,它显示崩溃Invalid top-level type in JSON write'我知道我的传递参数存在问题。请帮帮我!。怎么做。请帮帮我!!!

这是我传递的参数的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",
            "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....")
                            if (json["CartID"] as? Int?) != nil
                            {
                                DispatchQueue.main.async(execute: {

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


                                })
                            }

                        }

                    }
                })

            }
        })

        dataTask.resume()
    }
}

附加值的最后一个问题:

enter image description here

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

class Addtocartmodel

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

2 个答案:

答案 0 :(得分:7)

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

代码如下所示:

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()
    }
}

答案 1 :(得分:2)

存在细微差别

尝试使用此

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

而不是

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