如何在Swift中将对象数组发送到服务器? [英] How to send an array of objects to server in Swift?

查看:59
本文介绍了如何在Swift中将对象数组发送到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我应该发送这样的数据的后端信息.

这是我的代码:

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")

请帮助我.

解决方案

一种典型的遵循方法是使用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.

I want to send a list of the array to the server but I have troubles on it.

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

This is my code:

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")

Please help me.

解决方案

A typical approach to be followed is to use the Encodable, you'll be able to get the desired JSON string without the need of the tedious manual handling.

First, you should define the struct for the request (and let it conforms to Encodable):

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

then you could directly use it after setting the desired info:

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")

hence

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

As you can see, the output of logging printing resultString would be:

[{"startTime":"8:00PM","typeId":"10","originName":"Origin Name","startDate":"1/1/2018","destinationName":"Destination Name","passengerNumber":"2"}]


Note that I encoded as an array (try encoder.encode([myRequestObject])), if you are aiming to get a single object, you could simply implement it as:

let result = try encoder.encode(myRequestObject)

Also, you could -obviously- add more that just one object to the encoded array:

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

which myRequestObject, myRequestObject2 and myRequestObject3 are typed as RequestFormat.

这篇关于如何在Swift中将对象数组发送到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆