Ios 是否使用JSONSerialization附加NSMutableData?
服务器需要一个名为json的变量,其值为json对象。如何获取json对象并将其分配给变量json,然后将其发布到服务器?我在谷歌上搜索了这个问题,找到了代码,但它在目标c中Ios 是否使用JSONSerialization附加NSMutableData?,ios,json,swift,Ios,Json,Swift,服务器需要一个名为json的变量,其值为json对象。如何获取json对象并将其分配给变量json,然后将其发布到服务器?我在谷歌上搜索了这个问题,找到了代码,但它在目标c中 NSError *jsonError = nil; NSData *jsonObject = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&jsonError]; if (!jsonError) { NSMutableDa
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];
}
我正在用斯威夫特做这件事
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()
}
}
func post(){
让url:String=”http://example.com/test.php"
//-----我试过了
让json:String=“json=”;
让jsonString=json.dataUsingEncoding(NSUTF8StringEncoding)
//----结束尝试------------------
let request=NSMutableURLRequest(URL:NSURL(string:URL)!)
让params=[“email”:“jameson”,“password”:“password”]作为字典
//let request=NSMutableURLRequest(URL:URL)
let session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
做{
let data=尝试NSJSONSerialization.dataWithJSONObject(参数,选项:。预打印)
让dataString=NSString(数据:data,编码:NSUTF8StringEncoding)!
打印(“数据字符串为\(数据字符串)”)
request.HTTPBody=尝试NSJSONSerialization.dataWithJSONObject(参数,选项:。预打印)
}抓住{
//处理错误。可能将函数返回或标记为抛出
打印(错误)
返回
}
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
让task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
//处理错误
保护错误==nil else{return}
打印(“响应:\(响应)”)
让strData=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“正文:\(标准数据)”)
让json:NSDictionary?
做{
json=尝试NSJSONSerialization.JSONObjectWithData(data!,选项:.MutableLeaves)作为NSDictionary
}捕获let数据错误{
//JSONObjectWithData构造函数是否返回错误?如果是,请将错误记录到控制台
打印(数据错误)
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法分析JSON:'\(jsonStr)'”)
//回击还是投掷?
返回
}
//JSONObjectWithData构造函数没有返回错误。但是,我们仍然应该
//使用可选绑定检查并确保json具有值。
如果让parseJSON=json{
//好的,parsedJSON在这里,让我们从中获得“成功”的价值
让success=parseJSON[“success”]作为?Int
打印(“成功:\(成功)”)
}
否则{
//哇,好吧,json对象为零,出现了问题。可能服务器没有运行?
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法解析JSON:\(jsonStr)”)
}
})
task.resume()
}
}
我试图声明一个值为
“json=“
的字符串,但在此之后,我不知道如何制作NSMUTABLEDATA
,将其附加到NSJSONSerialization
中,然后在Swift中将可变数据设置到requestbody中,如果这是我完成任务所必须做的事情,您是如何尝试的?你有postBody
代码可以使用,很抱歉我没有收到你的邮件。你能再解释一下吗@如果obj-c中的示例代码中有一部分用于postBody
,您知道这就是您需要在swift中复制的内容,请尝试一下