Skip to content

Instantly share code, notes, and snippets.

@syed-afraz-ali
Created February 15, 2016 04:23
Show Gist options
  • Save syed-afraz-ali/05b31014a763662759d9 to your computer and use it in GitHub Desktop.
Save syed-afraz-ali/05b31014a763662759d9 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();
}
}
@AdilakshmiGit
Copy link

Hi,

jsonWriter.WritePropertyName(rdr.GetName(i))

can we read only value with out property.. As my returned value is from forjsonpath so it will return some generated column name. So i do not want to include it in my result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment