【问题标题】:Invalid top-level type in JSON write'JSON 写入中的顶级类型无效'
【发布时间】:2017-03-05 03:26:58
【问题描述】:

我将一些参数传递给 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()
    }
}

附加值的最后一个问题:

在我的模型数据类中是这样的:

class Addtocartmodel

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

【问题讨论】:

  • 那么你得到错误的真正原因是什么?

标签: ios json swift


【解决方案1】:

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

【讨论】:

  • 所以jsonstr是我传递给api的参数吧>>
  • 我是 ios 新手,我不知道如何使用 http 方法传递给我的 api。您能否也用我的 do catch 来编辑您的解决方案。这样有助于理解它的流程
  • 感谢您的解决方案,我已经使用了。将参数传递给 api 后,我会像这样得到{ "status": 1, "message": "Cart values has been added successfully.", "CartID": 5 }。但我没有得到它,也没有进入我的数据库
  • 我需要存储这个 cartID 值,否则必须附加到我的模型数据类中。
  • 是的,现在我得到了购物车 ID。但是当我添加它时,它不会添加到我的模型数据类值中
【解决方案2】:

有细微差别

试试这个

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

而不是

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

【讨论】:

猜你喜欢
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多