JSON写入中的无效顶级类型' [英] Invalid top-level type in JSON write'

查看:146
本文介绍了JSON写入中的无效顶级类型'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 know there is the problem in my passing parameter . Please help me out!.How to do that.Please help me out !!!

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

This is the json format of parameter i am passing !!:

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

附加值中的最后一个问题:

last problem in append the values :

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

In my model data class is look like this :

class Addtocartmodel

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

推荐答案

您的json格式有误.迅速使用字典比json清晰得多,并使用JSONSerialization将字典转换为json字符串.

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.

代码如下:

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

这篇关于JSON写入中的无效顶级类型'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆