title: JSON.NET: How to serialize just one row from a DataTable object without it being in an array?
body: <p>I have a database class that calls into a database and retrieves data. The data is loaded into a <code>DataTable</code> object with an <code>SqlDataAdapter</code>. I then want to take only the first row of data (in truth, the database will only ever return one row anyway) and convert it to a JSON string.</p>
  
  <p>The problem is this: If I simply pass the <code>DataTable</code> into the <code>JsonConvert.SerializeObject</code> method, e.g. <code>JsonConvert.SerializeObject(dt)</code>, I get a JSON string but it is an array with one object. For example:</p>
  
  <pre><code>[ {"id":"1","value":"hi"} ]
  </code></pre>
  
  <p>The code on the other end that expects to receive this JSON does not want an array, it simply wants an object. So basically I need the above, but without the square brackets <code>[</code> and <code>]</code>. So the desired output is:</p>
  
  <pre><code>{"id":"1","value":"hi"}
  </code></pre>
  
  <p>The naive approach I am using right now is to just return <code>result.Substring(1,result.Length - 2)</code> to the caller. Assuming that the JSON object exists in a single array of just one object, this has the effect of stripping the <code>[</code> and <code>]</code> off the return text. But it seems like there should be a "proper" way to achieve this.</p>
  
  <p>The most obvious thing would seem to be using the <code>Rows</code> property of the DataTable. However, if I try to do <code>JsonConvert.SerializeObject(dt.Rows[0])</code>, I don't get just the row, I get an entire collection of data about the state of the row, with one item being <code>Table</code> but which simply references the entire table, so in the event that more than one row occurred I would get all the rows, not just the one I desired.</p>
  
  <p>The other approach I have tried is to round-trip into JSON from the entire <code>DataTable</code>. I serialize the <code>DataTable</code>, then parse the result into into a <code>JArray</code> so I can get the first value, then reserialize again. But this seems unnecessary. </p>
  
  <p>Here's what trying to serialize a <code>Row</code> object gives me:</p>
  
  <pre><code>{
      "RowError":"",
      "RowState":2,
      "Table":[
          {
              "id":"1",
              "value":"hello"
          }
      ],
      "ItemArray":[
          "1","hello"
      ],
      "HasErrors":false
  }
  </code></pre>
  
  <p>Can I do this the "correct" way without just stripping the <code>[</code> and <code>]</code> off the string? In other words, can I get the data from one row of a <code>DataTable</code> as a single JSON object, not in an array, without roundtripping through JSON and back again just to pick it off the one-item array?</p>