服务器需要一个名为json的变量,其值为json对象。如何获取json对象并将其分配给变量json,然后将其发布到服务器?我已经搜索了这个问题,我找到了代码,但它的目标是c
NSError *jsonError = nil;
NSData *jsonObject = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&jsonError];
if (!jsonError) {
NSMutableData *postBody = [[NSMutableData alloc] initWithData:[@"json=" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:jsonObject];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:theURL];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postBody];
}
我在swift中这样做
func post() {
let url:String = "http://example.com/test.php"
//-----here i have tried
let json:String = "json=";
let jsonString = json.dataUsingEncoding(NSUTF8StringEncoding)
//----end trying----------------
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let params = ["email":"jameson", "password":"password"] as Dictionary<String, String>
//let request = NSMutableURLRequest(URL:url)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
do {
let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
print("dataString is \(dataString)")
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
} catch {
//handle error. Probably return or mark function as throws
print(error)
return
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// handle error
guard error == nil else { return }
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
let json: NSDictionary?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let dataError {
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
print(dataError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
// return or throw?
return
}
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
let success = parseJSON["success"] as? Int
print("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
}
})
task.resume()
}
}
我尝试声明一个值为"json="
的字符串但在此之后我不知道如何制作NSMUTABLEDATA
,将其附加到NSJSONSerialization
然后设置可变项数据到Swift中的请求主体,如果这是我必须做的事情来完成我的任务