Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct to json like Stringify in javascript [duplicate]

Tags:

json

swift

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)
}
like image 716
Chris G. Avatar asked Jul 12 '26 21:07

Chris G.


1 Answers

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]
        }
    }
}
like image 80
Moriya Avatar answered Jul 15 '26 18:07

Moriya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!