Created
February 15, 2016 04:23
-
-
Save syed-afraz-ali/05b31014a763662759d9 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
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.