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.
My problem is, I get an error during the NSJSONSerialization stating that top level typ is wrong. This is the exact error:
NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write
Below is my struct and my toJSON() function, which gives the named error.
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() -> 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
}
}
}
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:
invalid-top-level-type-in-json-write
Best regards,
Chris