如何在Swift中将对象数组发送到服务器?

时间:2018-07-01 06:50:35

标签: ios arrays json swift xcode

我想将阵列列表发送到服务器,但是遇到麻烦。

This is my backend information that I should send data like this.

这是我的代码:

loadRequest(request: "/tripTemporary/", parameters:
                ["startDate":"\(FindDriverViewController.dateToGo)",
                 "startTime":"\(FindDriverViewController.timeTOGo)",
                 "passengerNumber":"\(FindDriverViewController.PasengerCount)",
                 "typeId":"\(ServiceModeViewController.serviceMode)",
                 "originName":"\(MapViewController.sourceCity)",
                 "destinationName":"\(MapViewController.destinationCity)",
                 "passengerId":"\(ViewController.id)",
                    "tripCheckPoints":"{['address':'\(MapViewController.source)','longitude':'\(MapViewController.sourceLng)','latitude':'\(MapViewController.sourceLat)'],['address':'\(MapViewController.destination)','longitude':'\(MapViewController.Destinationlng)','latitude':'\(MapViewController.DestinationLat)']}"

                ],
                        json: true, get: false, callback: { (data) in

                            print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
            }, method: "POST")

请帮助我。

1 个答案:

答案 0 :(得分:0)

要遵循的典型方法是使用Encodable,无需繁琐的手动处理即可获得所需的JSON字符串。

首先,您应该为请求定义结构(并使其符合Encodable):

struct RequestFormat: Encodable {
    var startDate: String
    var startTime: String
    var passengerNumber: String
    var typeId: String
    var originName: String
    var destinationName: String
}

然后您可以在设置所需的信息后直接使用它:

let encoder = JSONEncoder()
// dummy values
let myRequestObject = RequestFormat(startDate: "1/1/2018",
                                    startTime: "8:00PM",
                                    passengerNumber: "2",
                                    typeId: "10",
                                    originName: "Origin Name",
                                    destinationName: "Destination Name")

因此

do {
    let result = try encoder.encode([myRequestObject])
    if let resultString = String(data: result, encoding: .utf8) {
        print(resultString)
    }
} catch {
    print(error)
}

如您所见,日志记录打印resultString的输出为:

  

[{“ startTime”:“ 8:00 PM”,“ typeId”:“ 10”,“ originName”:“来源   名称”,“ startDate”:“ 1/1/2018”,“ destinationName”:“ Destination”   名称”,“ passengerNumber”:“ 2”}]


请注意,我编码为数组(try encoder.encode([myRequestObject])),如果您打算获取单个对象,则可以将其实现为:

let result = try encoder.encode(myRequestObject)

此外,您可以-显然-仅将一个对象添加到编码数组中即可

let result = try encoder.encode([myRequestObject, myRequestObject2, myRequestObject3])

其中myRequestObjectmyRequestObject2myRequestObject3被键入为RequestFormat