如何在SWIFT中发送JSON字典数组 - (POST方法)

时间:2017-08-01 13:02:24

标签: ios json swift dictionary post

我想知道如何在JSON中发送多个字典数组。我必须以这种格式进行POST:

{
  "Account":
  {
    "lastname":"VVV",
    "PersonEmail":"vaaaay@gmail.com"
  },
  "Member":
  {
    "Password__C":"12345"
  },
  "ProgramName":"My Chili's"
}

这是我到目前为止所做的:

  lname = lastName.text!
        fname = firstName.text!
        email = emailSignUp.text!
        pass = passwordSignup.text!

        let signUpDict : [String:Any] =
       [
            "Account": [
            "lastname": lname!,
            "PersonEmail": email!
            ],

            "Member": [
                "Password__C": pass!
            ],

            "ProgramName": "My Chilli's"
        ]



var urlRequest = URLRequest(url: URL(string: url)!)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json;application/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
do{
    let postData = try? JSONSerialization.data(withJSONObject: signUpDict, options: JSONSerialization.WritingOptions.prettyPrinted)
    urlRequest.httpBody = postData

}
catch {
    print("Couldnt post this")
}



let task = URLSession.shared.dataTask(with:urlRequest as URLRequest){(data,response,error) in

    if error != nil{

        print("Error is \(error)")
        return
    }


    print("Data Responded : \(data)")
    print("response is: \(response)")

}

task.resume()

我在回复时遇到500错误。

{ status code: 500, headers {
    "Cache-Control" = "s-maxage=0";
    "Content-Security-Policy" = "referrer origin-when-cross-origin";
    "Content-Type" = "application/json;charset=UTF-8";
    Date = "Tue, 01 Aug 2017 12:19:44 GMT";
    "Transfer-Encoding" = Identity;
    "X-XSS-Protection" = "1; mode=block";
} })

我认为我写signUpDict的方式可能不正确或缺少某些内容,有人可以指导我完成这个吗?

修改 根据要求我在POSTMAN上尝试了json,但这是我第一次使用POSTMAN(完全新手)。所以我不确定我是否做得对。

POSTMAN screenshot

3 个答案:

答案 0 :(得分:0)

请尝试使用此更新代码

   lname = lastName.text!
   fname = firstName.text!
   email = emailSignUp.text!
   pass = passwordSignup.text!

   let signUpDict : [String:Any] =
    [
        "Account": [
            "lastname": lname!,
            "PersonEmail": email!
        ],

        "Member": [
            "Password__C": pass!
        ],

        "ProgramName": "My Chilli's"
   ]




    let data = try! JSONSerialization.data(withJSONObject: signUpDict, options: JSONSerialization.WritingOptions.prettyPrinted)

    let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
    if let json = json {
        print(json)
    }

    let jsonData = json!.data(using: String.Encoding.utf8.rawValue);

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = HTTPMethod.post.rawValue
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")

    request.httpBody = jsonData

答案 1 :(得分:0)

替换以下行:

发件人

urlRequest.setValue("application/json;application/html; charset=utf-8", forHTTPHeaderField: "Content-Type")

urlRequest.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")

答案 2 :(得分:0)

试试这个: -

lname = lastName.text!
   fname = firstName.text!
   email = emailSignUp.text!
   pass = passwordSignup.text!


let accountDict = NSMutableDictionary.init()
let memberDict = NSMutableDictionary.init()
let finalDict = NSMutableDictionary.init()
accountDict.setValue(lname, forKey: "lastname")
accountDict.setValue(email, forKey: "PersonEmail")
 memberDict.setValue(pass, forKey: "Password__C")
 finalDict.setValue(accountDict, forKey: "Account")
 finalDict.setValue(memberDict, forKey: "Member")
finalDict.setValue("My Chili's", forKey: "ProgramName")
print(finalDict)

let data = try! JSONSerialization.data(withJSONObject: finalDict, options: JSONSerialization.WritingOptions.prettyPrinted)

    let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
    if let json = json {
        print(json)
    }

    let jsonData = json!.data(using: String.Encoding.utf8.rawValue);

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = HTTPMethod.post.rawValue
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")

    request.httpBody = jsonData