您的位置:首页 > Web前端 > JavaScript

通过nsurlsession向服务器传送json数据

2015-12-26 20:19 676 查看
近几天真是被json搞死了 终于知道该怎么用json向服务器传输json了 直接贴代码吧

//多样性的request
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:4567/login")!)
let session = NSURLSession.sharedSession()
let params = ["uername":"jameson","password":"cao"]
//默认是get
request.HTTPMethod = "POST"
//核心 将字典或者数组转化成为json
do {request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
}
catch{
print("error")
}
//这里还不造啥意思
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
var strData = String(data: data!, encoding: NSUTF8StringEncoding)
post(params, url: "http", postCompleted: { (succeed, msg) -> () in

})

}
//用闭包作为参数 还是第一次用
func post(params:Dictionary<String,String>,url:String,postCompleted:(succeed:Bool,msg:String) -> ()) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:4567/login")!)
let session = NSURLSession.sharedSession()
let params = ["uername":"jameson","password":"cao"]
//默认是get
request.HTTPMethod = "POST"
do {request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
}
catch{
print("error")
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
var strData = String(data: data!, encoding: NSUTF8StringEncoding)
do {var jsondata = try NSJSONSerialization.JSONObjectWithData(data! , options: .AllowFragments) as! NSDictionary

}
catch{
print("error")
}

}
NSJSONSerialOption是解析或者创建json时候用到的 datawithobject是创建json 后面的option采用的是writing 的.prettyprinted采用的是格式化输出json

读取的时候用的是jsonobjectwithdata 后面的readingoption有三种 常用的是allowframts 好像顶层不是array或者dictionary都可以变成数组等 具体以后再补!

NSJSONReadingMutableContainers:返回可变容器,NSMutableDictionary或NSMutableArray

http://stackoverflow.com/questions/19345864/nsjsonreadingmutableleaves-option-is-not-working

NSJSONReadingMutableLeaves:返回的JSON对象中字符串的值为NSMutableString,目前在iOS
7上测试不好用,应该是个bug,

http://stackoverflow.com/questions/19345864/nsjsonreadingmutableleaves-option-is-not-working

NSJSONReadingAllowFragments:允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON
Fragment。例如使用这个选项可以解析 @“123” 这样的字符串。

http://stackoverflow.com/questions/16961025/nsjsonserialization-nsjsonreadingallowfragments-reading
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: