从DataReader中手动串行化JSON

void WriteDataReader(StringBuilder sb, IDataReader reader)
{
    if (reader == null || reader.FieldCount == 0)
    {
        sb.Append("null");
        return;
    }

    int rowCount = 0;

    sb.Append("{\"Rows\":[\r\n");

    while (reader.Read())
    {
        sb.Append("{");
        
        for (int i = 0; i < reader.FieldCount; i++)
        {
            sb.Append("\"" + reader.GetName(i) + "\":") ;
            this.WriteValue(sb,reader[i]);
            sb.Append(",");
            if (this.FormatJsonOutput)
                sb.Append("\r\n");                    
        }
        // strip off trailing comma
        if (reader.FieldCount > 0)
            this.StripComma(sb);

        sb.Append("},");
        if (this.FormatJsonOutput)
            sb.Append("\r\n");
        
        rowCount++;
    }

    // remove trailing comma
    if (rowCount > 0)
        this.StripComma(sb);

    sb.Append("]}");
}

 

posted @ 2016-06-07 17:12  落叶的瞬间;  阅读(500)  评论(0编辑  收藏  举报