Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gino8080/ba42bbb58a10633f24e58e14c7c12801 to your computer and use it in GitHub Desktop.
Save gino8080/ba42bbb58a10633f24e58e14c7c12801 to your computer and use it in GitHub Desktop.
Convert SqlDataReader to Json String
// Requires Newtonsoft.Json to create JSON String
public static String ToJson(this SqlDataReader rdr)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
while (rdr.Read())
{
jsonWriter.WriteStartObject();
int fields = rdr.FieldCount;
for (int i = 0; i < fields; i++)
{
jsonWriter.WritePropertyName(rdr.GetName(i));
jsonWriter.WriteValue(rdr[i]);
}
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndArray();
return sw.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment