public string toJSON(SqlDataReader o)
{
StringBuilder s = new StringBuilder();
s.Append(\"[\");
if (o.HasRows)
while (o.Read())
s.App
I encounter use cases where the number of rows being returned by the data reader may become problematic with respect to memory consumption. The following code uses a JsonWriter (from JSON.NET) over a stream. One can certainly debate the utility of enormous JSON documents, but sometimes our use cases are dictated by others :-)
A few notes:
The code:
var stream = ... // In my case, a FileStream or HttpResponse stream
using (var writer = new JsonTextWriter(new StreamWriter(stream)))
{
writer.WriteStartObject();
do
{
int row = 0;
string firstColumn = null;
while (await reader.ReadAsync())
{
if (row++ == 0)
{
firstColumn = reader.GetName(0);
writer.WritePropertyName(string.Format("{0}Collection", firstColumn));
writer.WriteStartArray();
}
writer.WriteStartObject();
for (int i = 0; i < reader.FieldCount; i++)
{
if (!reader.IsDBNull(i)) {
writer.WritePropertyName(reader.GetName(i));
writer.WriteValue(reader.GetValue(i));
}
}
writer.WriteEndObject();
}
writer.WriteEndArray();
} while (await reader.NextResultAsync());
writer.WriteEndObject();
}
An example of heterogeneous output would be:
{
"ContactCollection": {
"ContactItem": [{
"ContactID": "1",
"Contact": "Testing",
},
{
"ContactID": "2",
"Contact": "Smith, John",
},
{
"ContactID": "4",
"Contact": "Smith, Jane",
}
],
"MessageItem": [{
"MessageID": "56563",
"Message": "Contract Review Changed",
},
{
"MessageID": "56564",
"Message": " Changed",
},
{
"MessageID": "56565",
"Message": "Contract Review - Estimated Completion Added.",
}
]
}
}
Reference: