我是json和swift的新手 我想在服务器上发送json格式的数据和标头 这是代码
"Destination":{"ContactPerson":"Garry Jackson","Address":{"PostCode":"4104","StreetAddress":"Bay View","Suburb":"BAY VIEW","BuildingName":"15 Le Quesne Rd","City":"NAPIER","CountryCode":"NZ"},"PhoneNumber":"027 3356871","Email":"jacko.bv@xtra.co.nz","Name":"Garry Jackson"}
let parameters = [
"Packages" : ["Length" : Length, "Type" : "", "Kg" : Weight, "Height" : Height, "Width" : Width, "Name" : SkuName],
"issignaturerequired" : true,
"Outputs":["LABEL_PNG_100X175"],
"DeliveryReference":86882,
"Destination":["ContactPerson":self.CustomerFirstname,
"Address":["PostCode":self.PostalCode,"StreetAddress":self.Address1,"Suburb":self.City,"BuildingName":"ABC","City":self.City,"CountryCode":"AU"],
"PhoneNumber":9998406081,"Email":self.CustomerEmail,"Name":self.CustomerFirstname],
"PrintToPrinter":true,
"SendTrackingEmail":"",
"Commodities":[["UnitKg":1.0000,"Currency":"NZD","Country":"NZ","Units":1,"Description":"Drums Drum Accessories Drum Bags","UnitValue":44.0],["UnitKg":1.0000,"Currency":"NZD","Country":"NZ","Units":1,"Description":"Drums Drum Accessories Drum Bags","UnitValue":44.0]],
"DeliveryInstructions":"None"
]
let headers = [
"Content-Type" : "application/json",
"Access_Key":"Key"
]
Alamofire.request(.POST, "http://api.omniparcel.com/labels/printcheapestcourier", headers: headers, parameters: parameters).responseJSON {
response in
print(response)
let json = JSON(response.data!) //SwiftyJSON
}
如何在swift中发布此数据
答案 0 :(得分:0)
你可以使用Alamofire。 https://github.com/Alamofire/Alamofire
var parameters : [String : AnyObject] = [
"PackageA" : [["Length" : length, "Type" : type, "Kg" : kg, "Height" : height, "Width" : width, "Name" : name]],
"issignaturerequired" : "true",
//Put all your other JSON properties here
]
Alamofire.request(.POST, "http://api.omniparcel.com/labels/printcheapestcourier", parameters: parameters, encoding: .JSON)
.responseJSON { response in
if let JSON = response.result.value {
print(JSON);
}
}
答案 1 :(得分:0)
您可以使用Alamofire进行HTTPRequest,使用SwiftyJSON来解析返回的json。或者使用NSURLSession
并在swift中反序列化JSON
。 (您可以搜索S.O.以获取一些示例)
let parameters = [
"Packages": [
"length": myLengthVariable,
"type": "kg"
//add parameters here
]
]
let headers = [
"Content-Type: application/json"
//add addition headers here
]
Alamofire.request(.GET, "http://api.omniparcel.com/labels/printcheapestcourier", headers: headers, parameters: parameters).responseJSON {
response in
let json = JSON(response.data) //SwiftyJSON
//Do whatever you want with the json here
}