2016-10-23 4 views
4

私はいくつかのパラメータをAPIに渡しています。カートに追加機能が完了しました。しかし、私はパラメータを渡すと、それはクラッシュを示してInvalid top-level type in JSON write'私は渡すパラメータに問題があることを知っている。私を助けてください!。それを行う方法。私を助けてください!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", 
      "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() 
    } 
} 

最後の問題APPENDの値:

enter image description here

私のモデルでは、データクラスは次のようになります:

class Addtocartmodel 

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

答えて

2

あなたのJSON辞書format.Use一部の間違ったでは迅速で、JSONよりもはるかに明確であり、JSON文字列に辞書を変換するJSONSerializationを使用しています。

コードは次のようになります。私は、IOSに新しいです

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

のでjsonstrは、適切なAPIに渡すために私のパラメータです>> – mack

+0

、私は私のAPIに渡すことHTTPメソッドを実行する方法を知りません。私もあなたの解決策を編集してください。それはそれの流れを理解するのに役立つように – mack

+0

OK、私は私の答えを更新しました。 –

関連する問題