title: How to generate JSON string in Swift 3?
body: <p>I am trying to send a request to an API that requires this format:</p>
  
  <pre><code>{
      "inputs": [
          {
              "data": {
                  "image": {
                      "base64": "iVBORw0KGgoAAAIVnFT/DPAAAAAElFTkSuQmCC..."
                  }
              }
          }
      ]
  }
  </code></pre>
  
  <p>This is what I tried in Swift 3:</p>
  
  <pre><code>let base64 = ["base64": "1010101..."]
  
  let image: [String: Any] = ["image": base64]
  
  let data: [String: Any] = ["data": image]
  
  var input = [Dictionary&lt;String, Any&gt;]()
  
  input = [data]
  
  let jsonData = try! JSONSerialization.data(withJSONObject: input, options: .prettyPrinted)
  </code></pre>
  
  <p>I got an invalid request error when trying to hit the endpoint. Not surprising - when I printed it:</p>
  
  <pre><code>let jsonString = try! JSONSerialization.jsonObject(with: jsonData, options: [])
  
  print(jsonString)
  </code></pre>
  
  <p>It produced a string like this:</p>
  
  <pre><code>(
          {
          data =         {
              image =             {
                  base64 = 1010101;
              };
          };
      }
  )
  </code></pre>
  
  <p>For now, I am rolling my own string. It works...but it's ugly as hell and just really not tenable.</p>
  
  <pre><code>let imageAsString = "{\"inputs\": [{\"data\": {\"image\": {\"base64\": \"\(strBase64)\"}}}]}"
  </code></pre>
  
  <p>My other thought was that I could create a series of embedded objects: a Data object that holds a dictionary; an Image object that holds a Data object; and an Inputs object that holds an array of Data objects. </p>
  
  <pre><code>class Image {
      var base64 = Dictionary&lt;String, String&gt;()
  }
  
  class Data {
      var image = Image()
  }
  
  class Inputs {
      var inputs = [Data]()
  }
  </code></pre>
  
  <p>But initializing them all and calling <code>JSONSerialization.data</code> doesn't work as this takes a dictionary object. </p>
  
  <p>I'm not really interested in pulling in 3rd party plugins for now. Any ideas on how to convert these nested objects into json using the native iOS libraries?</p>