Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@AdilakshmiGit AdilakshmiGit commented May 31, 2018

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