3

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?

1 Answer 1

4

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Smashing. I though it had to be something simple I was doing wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.