swift error: Invalid top-level type in JSON write
<p>I have a structure within my swift class that shall describe a card and I want to have it as a JSON which shall be written out to a file on save.</p>

<p>My problem is, I get an error during the NSJSONSerialization stating that top level typ is wrong. This is the exact error:</p>

<pre><code>NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write
</code></pre>

<p>Below is my struct and my toJSON() function, which gives the named error.</p>

<pre><code>struct CardStructure {
   var UUID: NSUUID = NSUUID.init()
   var Chapter: Int = 0
   var Card: Int = 0
   var CorrectAnswers: Int = 0
   var WrongAnswers: Int = 0
   var Unknown: Int = 0
   var LastAsked: String = ""
   var Question: String = ""
   var Answer: String = ""
   var Hint: String = ""
   var Tags: [String] = []
   var Links: [String] = []
   var Picture: String = ""

    func toJSON() -&gt; String? {
        let props = ["UUID": String(describing: UUID),
                     "Chapter": Chapter,
                     "Card": Card,
                     "Question": Question,
                     "Answer": Answer,
                     "Hint": Hint,
                     "Tags": Tags,
                     "Links": Links,
                     "Picture": Picture
                     ] as [String : Any]
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: props,
                                                                      options: .prettyPrinted)
            return String(data: jsonData, encoding: String.Encoding.utf8)
        } catch let error {
            print("error converting to json: \(error)")
            return nil
        }
    }
}
</code></pre>

<p>I'm fairly new to swift and have no clue why this error is caused. Can anyone help me??? I tried to understand tips in other posts regarding this error, but so far, my knowledge on swift is too low, to adapt solutions provided, like this one in the link:</p>

<p><a href="https://stackoverflow.com/questions/34205813/invalid-top-level-type-in-json-write">invalid-top-level-type-in-json-write</a></p>

<p>Best regards,</p>

<p>Chris </p>