title: Serialize [String:Any] to JSON
body: <p>I'm trying out Swift on Linux. </p>
  
  <p>I have data in the form of dictionaries with String keys, and values of Any type, and am trying to serialize these to a String in JSON format. </p>
  
  <p><code>NSJSONSerialization.dataWithJSONObject</code> did not work, it complains 
  <code>Argument type '[String : Any]' does not conform to expected type 'AnyObject'</code></p>
  
  <pre><code>let dict : [String : Any] = [
      "string" : "Hello",
      "int" : 1,
      "double" : 3.14,
      "array str" : ["a", "b", "c"],
      "array double" : [1.0, 2.0, 3.0],
      "array int" : [1, 2, 3]
  ]
  </code></pre>
  
  <p>I know it must be doable, as the string representation of the dictionary is already almost in the right format: </p>
  
  <pre><code>print("\(dict)")
  ["array int": [1, 2, 3], "int": 1, "array double": [1.0, 2.0, 3.0], "string": "Hello", "double": 3.1400000000000001, "array str": ["a", "b", "c"]]
  </code></pre>
  
  <p>Before you suggest declaring dict as a <code>[String:AnyObject]</code>, the dictionary is filled from dynamic data, not declared as a literal. </p>
  
  <p>If possible, I'd like to limit the use of OSX or iOS specific libraries that might not be available on the server. </p>
  
  <p><strong>Edit:</strong> </p>
  
  <p>Here's an implementation of the solution proposed by Enrico Granata:</p>
  
  <pre><code>protocol JSONSerializable {
      func toJSON() -&gt; String?
  }
  
  extension String : JSONSerializable {
      func toJSON() -&gt; String? {
          return "\"\(self)\""
      }
  }
  
  extension Int : JSONSerializable {
      func toJSON() -&gt; String? {
          return "\(self)"
      }
  }
  
  extension Double : JSONSerializable {
      func toJSON() -&gt; String? {
          return "\(self)"
      }
  }
  
  extension Array : JSONSerializable {
      func toJSON() -&gt; String? {
          var out : [String] = []
          for element in self {
              if let json_element = element as? JSONSerializable, let string = json_element.toJSON() {
                  out.append(string)
              } else {
                  return nil
              }
          }
          return "[\(out.joinWithSeparator(", "))]"
      } 
  }
  
  extension Dictionary : JSONSerializable {
      func toJSON() -&gt; String? {
          var out : [String] = []
          for (k, v) in self {
              if let json_element = v as? JSONSerializable, let string = json_element.toJSON() {
                  out.append("\"\(k)\": \(string)")
              } else {
                  return nil
              }
          }
          return "{\(out.joinWithSeparator(", "))}"
      }
  }
  </code></pre>