How can you convert a struct to json. Like Stringify in javascript?
Following gives the error: Argument type 'MyStruct' does not conform to expected type 'AnyType.
I get that, but how would you do it?
struct MyStruct{
var name: String
}
let obj = MyStruct(name: "Bob")
let data = try NSJSONSerialization.dataWithJSONObject(obj, options: .PrettyPrinted)
if let string = NSString(data: data, encoding: NSUTF8StringEncoding){
print(string)
}
Add a function or property to your struct that gives you a dictionary that you then can serialise.
struct MyStruct{
var name: String
var dictionary: [String: AnyObject]{
get {
return ["name": name]
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With