Home > ASP.NET > SqlDataReader to JSON string

SqlDataReader to JSON string

We can easily parse the SqlDataReader object to a JSON string , see the below code

private string WriteReaderToJSON(StringBuilder sb, IDataReader reader)
{

if (reader == null || reader.FieldCount == 0)
{
sb.Append(“null”);
return “”;
}

int rowCount = 0;

sb.Append(@”{“”Rows””:[“);

while (reader.Read())
{
sb.Append(“{“);

for (int i = 0; i < reader.FieldCount; i++)
{
sb.Append(“\”” + reader.GetName(i) + “\”:”);
sb.Append(“\”” + reader[i] + “\””);

sb.Append(i == reader.FieldCount – 1 ? “” : “,”);

}

sb.Append(“},”);

rowCount++;
}

if (rowCount > 0)
{
int index = sb.ToString().LastIndexOf(“,”);
sb.Remove(index, 1);
}

sb.Append(“]}”);

return sb.ToString();

}

Advertisements
Categories: ASP.NET Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: