title: How can I parse a JSON string into a struct in swift?
body: <p>Here's the code I have so far:</p>
  <pre class="lang-swift prettyprint-override"><code>struct MyStruct {
      func readStream() {
          // AF is the AlamoFire library
          AF.streamRequest(&quot;https://example.com/stream/\(streamId)&quot;, headers: [.authorization(bearerToken: API_TOKEN)]).responseStreamString { stream in
              switch stream.event {
                  case let .stream(result):
                      // this is where I want to parse the result JSON string into a struct
                      print(result)
  
                  case .complete:
                      print(&quot;Stream ended, starting new request to continue reading data&quot;)
                      self.readStream()
              }
          }
      }
  }
  </code></pre>
  <p>The API I'm working with expects the client to open an HTTP connection, and then read events which come in as JSON strings—one per line.</p>
  <p>So far, I've done a bunch of Googling, for things like &quot;JSON String to struct&quot;. I learned that I need to set up a <code>Decodable</code> struct which matches my expected format for the <code>result</code> JSON string. But I'm stuck on how to convert the JSON String into that struct:</p>
  <pre class="lang-swift prettyprint-override"><code>struct StreamUpdate : Decodable{
      var timeElapsed: Int
      var totalSum: Int
      var medianSoFar: Int
  }
  </code></pre>
  <p>I've tried to use JSONDecoder, by replacing <code>print(result)</code> with:</p>
  <pre class="lang-swift prettyprint-override"><code>let parsedJson = try? JSONDecoder().decode(StreamUpdate.self, result.get())
  </code></pre>
  <p>This was recommended by Raildex in a comment and seems supported by <a href="https://developer.apple.com/documentation/foundation/jsondecoder" rel="nofollow noreferrer">these Apple docs</a>. But it causes an error:</p>
  <pre><code>Cannot convert value of type 'String' to expected argument type 'Data'
  </code></pre>