fabiossa
fabiossa

Reputation: 136

SwiftyJSON add array of JSON objects

I am trying to serialize my object graph into JSON using the SwiftyJSON Library. I have a function in a BirthdayEvent class named "toJSON" which converts individual Birthday Events into swiftyJSON objects successfully.

However I am keen to have something like the following structure to the JSON:

"birthdays" : [
    {
        "eventId": "...",
        "date": "01/01/2000",
        ...
    },
    {
        "eventId": "...",
        "date": "01/02/2001",
        ...
    },
    ...
]

I am finding it difficult to create a JSON dictionary with the String "birthday" as the key and the array of BirthdayEvent JSON items as the value.

I have the following code:

var birthdaysJSON: JSON = JSON(self.events.map { $0.toJSON() })
var jsonOutput : JSON = ["birthdays": birthdaysJSON]

The first line successfully creates a JSON object of the array of events, but I cannot seem to use this in the dictionary literal. I get an error of "Value of type 'JSON' does not conform to expected dictionary value type 'AnyObject'.

Can you tell me where I am going wrong, or am I over-complicating this?

Upvotes: 3

Views: 4524

Answers (1)

Wallace Campos
Wallace Campos

Reputation: 1301

To create a JSON dictionary, you have to initialize the JSON object on jsonOutput just like you did with birthdaysJSON:

var jsonOutput: JSON = JSON(["birthdays": birthdaysJSON])

Upvotes: 4

Related Questions