0

I am trying to convert a simple struct to JSON string. The struct looks like this:

struct MyStruct: Equatable {

let propertyA:Int
let propertyB:String
let propertyC:Double
//There are about ten more fields

func myStructMethod->String{
    return "return value"
    }
}

So, because the struct doesn't conform to AnyObject type (but rather to Any I guess) the simple conversion like this fails:

let data = try NSJSONSerialization.dataWithJSONObject(myStructArray, options: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)

Is there some way to skip creating JSON string "by the hand" (say using array map and building string by myself)?

Whirlwind
  • 14,286
  • 11
  • 68
  • 157

1 Answers1

-2

There is no such thing as a "JSON string". JSON documents are data.

JSON objects are strings, numbers, booleans, null values, arrays of JSON objects, dictionaries with string keys and JSON objects as values.

You convert anything you have into such a dictionary or array, then use NSJSONSerialization.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • Well, I haven't described everything correctly then. What I really need, is a string as an end result. But I get what you saying. I was trying to skip conversion from struct to dictionary. – Whirlwind Jul 23 '16 at 13:23