-
-
Save gino8080/ba42bbb58a10633f24e58e14c7c12801 to your computer and use it in GitHub Desktop.
Convert SqlDataReader to Json String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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