3

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)
}
Beraliv
  • 518
  • 7
  • 20
Chris G.
  • 23,930
  • 48
  • 177
  • 302
  • 1
    First, read this: [Swift: Convert struct to JSON?](http://stackoverflow.com/questions/33186051/swift-convert-struct-to-json) – Eric Aya Nov 18 '15 at 12:23
  • Then have a look at this: http://stackoverflow.com/questions/29625133/convert-dictionary-to-json-in-swift – Eric Aya Nov 18 '15 at 12:23

1 Answers1

2

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]
        }
    }
}
Moriya
  • 7,750
  • 3
  • 35
  • 53