I need to construct a JSON object in the format shown below.
{
"DeviceCredentials": {
"UniqueId": "sample string 1"
},
"Handovers": [
{
"Occasions": [
{
"Id": 1
},
{
"Id": 1
}
]
}
]
}
There is a issue though with the Occasions
array though. The number of Occasion
objects vary. Sometimes there can be only one Occasion, sometimes multiple. Since this is dynamic I wrote the below method to create this array.
func getOccasionArray(handover: Handover) -> JSON {
var occArray = [[String: NSNumber]]()
for occ in handover.occasions {
let occasion = occ as Occasion
var obj = ["Id": occasion.id!]
occArray.append(obj)
}
let json = JSON(occArray)
return json
}
I use the SwiftyJSON library to convert the created array to JSON. Here's the returned result of json
variable looks like for a Handover which has only one Occasion.
[
{
"Id" : 243468
}
]
So far so good. The problem is I'm having trouble plugging this into the bigger JSON response. Simply calling the method like this gives the error 'NSObject' does not have a member named 'Key'.
var parameters = [String: NSObject]()
parameters = [
"DeviceCredentials": [
"UniqueId": "1212121212"
],
"Handovers": [
[
"Occasions": getOccasionArray(handover)
]
]
]
I tried converting the returned value to an array getOccasionArray(handover).arrayValue
but no change.
Any idea on how to fix this?
Thanks.
parameters
variable's type asJSON
. You see I need to pass this JSON object as a parameter for a URL request. I use Alamofire for HTTP request handling and it only accepts parameter in[String: AnyObject]
format. – Salts