在iOS swift Json解析如何在post方法

时间:2015-05-25 10:55:42

标签: swift

在这里,我尝试使用手机号码注册应用程序,但我无法以正确的格式进行,我在Json解析注册应用程序时出错。

在这里,我给出了我尝试过的代码,

var request = NSMutableURLRequest(URL: NSURL(string: "http://app.mycompany.in/gcm/test_slim.php/register")!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)

var response: NSURLResponse?
var error: NSError?
var reponseError: NSError?

var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

// create some JSON data and configure the request

let jsonString = "json=[{\"gsm_number\":\(Mobile),\"name\":\(Name),\"email\":\(Email),\"status\":\(Status),\"ver_code\":,\"profile_picture\":,\"device_id\":,\"gcm\":,\"is_register\":,\"thumb_image\":,\"user_baground_img\":}]"

request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
    println("HTTP response: \(httpResponse.statusCode)")
    println("jsonString: \(jsonString)")
    var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

    let VerificationcodeViewController = self.storyboard?.instantiateViewControllerWithIdentifier("verificationcodeViewController") as UIViewController

    self.navigationController?.pushViewController(VerificationcodeViewController, animated: true)
} else {
    println("No HTTP response")
    var alertView:UIAlertView = UIAlertView()
    alertView.title = "Error!"
    alertView.message = "Error. & Some Problem was Found"
    alertView.delegate = self
    alertView.addButtonWithTitle("OK")
    alertView.show()
}

2 个答案:

答案 0 :(得分:1)

你不能有空钥匙,试试这个:

let parameters = [
    "gsm_number" : Mobile,
    "name" : Name,
    "email" : Email,
    "status" : Status,
]

let jsonData = NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.allZeros, error: nil)

let jsonString = "json=\(NSString(data: jsonData!, encoding: NSUTF8StringEncoding)!)"

答案 1 :(得分:1)

您的jsonString不符合JSON语法。

  1. 您不能在json=开头,=不是JSON中允许的分隔符,请使用:

  2. 你需要用双引号包装字符串变量(并转义它们)

  3. 如果缺少值,您就无法拥有空键,您必须使用null

  4. 变量的有效字符串示例:

    let jsonString = "[{\"gsm_number\":\(Mobile),\"name\":\"\(Name)\",\"email\":\"\(Email)\",\"status\":\(Status),\"ver_code\":null}]"
    

    或者使用' json'一开始就像你一样关键:

    let jsonString = "{\"json\":[{\"gsm_number\":\(Mobile),\"name\":\"\(Name)\",\"email\":\"\(Email)\",\"status\":\(Status),\"ver_code\":null}]}"
    

    将其放入Playground并在" View"中显示助理编辑器。菜单,它会帮助您理解:

    let Mobile = 42
    let Name = "James"
    let Email = "test@test.com"
    let Status = 200
    let jsonString = "[{\"gsm_number\":\(Mobile),\"name\":\"\(Name)\",\"email\":\"\(Email)\",\"status\":\(Status),\"ver_code\":null}]"
    let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    

    Swift 1

    var err: NSError?
    let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.allZeros, error: &err) as? [[String:AnyObject]]
    if err != nil {
        println(err)
    } else {
        println(json![0]["status"]!)
    }
    

    Swift 2

    do {
        if let data = data,
          let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String:AnyObject]] {
            if let status = json[0]["status"] as? Int {
                print(status)
            }
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }